Sorry for the question, probably it is answered within a few minutes.
I'm new to Android App development and have been searching for an answer for about 2 hours, but I don't find a solution.
So, this is my problem:
I created a MainActivity with a very simple layout, only one ToggleButton to start/stop some sound. I got it working with calling the MediaPlayer from within the MainActivity-Class.
Now I want to put the MediaPlayer-Handling into a separate class, such that it can be called from a widget as well.
When rising a Toast or calling a MediaPlayer-Method, I need to refer to the MainActivity, which was (in the MainActivity itself) "this".
But I don't know how to refer to the instance of the MainActivity.
The code is as follows:
package com.heavyloadreverse;
//import java.io.IOException;
import android.app.Activity;
//import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
//import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
//private MediaPlayer mp;
private Sound snd;
private ToggleButton btn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (ToggleButton) findViewById(R.id.btn_OnOff);
snd = new Sound();
snd.mp_create(MainActivity.this);
}
public void onToggleClicked(View v) {
// Perform action on clicks
if (((ToggleButton) v).isChecked()) {
snd.mp_start();
} else {
snd.mp_stop();
}
}
/*********************************************************************************
public void mp_create() {
mp = MediaPlayer.create(this, R.raw.truckreverse);
}
public void mp_start () {
Toast.makeText(this, R.string.start, Toast.LENGTH_SHORT).show();
// start the sound
mp.setLooping(true);
mp.start();
}
public void mp_stop () {
Toast.makeText(this, R.string.stop, Toast.LENGTH_SHORT).show();
// stop the sound
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void mp_init() {
btn.setChecked(false);
}
**********************************************************************************/
public void btn_init() {
btn.setChecked(false);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onRestart() {
super.onRestart();
btn_init();
}
#Override
public void onResume() {
super.onResume();
btn_init();
}
#Override
public void onPause() {
super.onPause();
snd.mp_stop();
}
#Override
public void onStop() {
super.onStop();
snd.mp_stop();
}
#Override
public void onDestroy() {
super.onDestroy();
snd.mp_stop();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
}
}
The class for the MediaPlayer-Handling:
package com.heavyloadreverse;
import java.io.IOException;
import android.app.Application;
import android.media.MediaPlayer;
import android.widget.Toast;
import com.heavyloadreverse.R;
public class Sound extends Application {
private MediaPlayer mp;
public void mp_create (MainActivity main) {
Toast.makeText(main.this, "test", Toast.LENGTH_SHORT).show();
mp = new MediaPlayer();
try {
mp = MediaPlayer.create(this, R.raw.truckreverse);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void mp_start () {
Toast.makeText(MainActivity.this, R.string.start, Toast.LENGTH_SHORT).show();
// start the sound
try {
mp.setLooping(true);
mp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void mp_stop () {
//Toast.makeText(this, R.string.stop, Toast.LENGTH_SHORT).show();
try {
// stop the sound
mp.stop();
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();
--> raises a runtime-error when executing:
--> 03-12 20:23:18.412: E/AndroidRuntime(862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.heavyloadreverse/com.heavyloadreverse.MainActivity}: java.lang.NullPointerException
Toast.makeText(main.this, "test", Toast.LENGTH_SHORT).show();
--> error in code:
--> *Multiple markers at this line
- main cannot be resolved to a type
- Line breakpoint:Sound [line: 15] -
mp_create(MainActivity)*
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
--> error in code:
--> No enclosing instance of the type MainActivity is accessible in scope
What do I have to do in order to make the Toast- and MediaPlayer-Calls in "Sound.java" working?
Thanks a lot in advance.
Sven
Option 1
Add 'Context' as a parameter on 'Sound'
public class Sound{
private Context mContext;
Sound(Context context){
mContext = context;
}
...
Toast.makeText(mContext, text, length).show();
...
}
When you create Sound from activity you will do it like new Sound(this);
Option 2
Define an interface in Sound to provide callbacks
public class Sound {
interface OnSoundListener{
public void onSoundStarted();
public void onSoundStopped();
}
}
And your main activity will look like
public class MainActivity implements Sound.OnSoundListener{
#Override
public void onSoundStarted(){
//your toast here
}
}
Personally I prefer the second one, that way you can separate logic from UI.
Not sure if this work, only an idea.
Firs of all extend your Sound class from your MainActivity
public class Sound extends MainActivity {
second, this is the code I use for Toast to work:
Toast.makeText(MainActivity.this,"Your Text Here",Toast.LENGTH_LONG).show();
For Toast this is what you need to do:
Toast toast=Toast.makeText(this, "Hello toast", 2000);
toast.show();
Check this tutorial tutorial if it helps.
Related
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.
there is a method to play a music when the splash screen is run?
this is my splash screen code:
// Splash screen timer
private static int SPLASH_TIME_OUT= 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Start main activity
Intent i = new Intent(SplashScreen.this, MyActivity.class);
startActivity(i);
// close activity
finish();
}
}, SPLASH_TIME_OUT);
}
I created the raw folder in res / raw and put in my song, how can I play it when the run splash screen?
Simply you can use,
myMediaPlayer = MediaPlayer.create(this, R.raw.loveme);
if (myMediaPlayer != null) {
myMediaPlayer.start();
} else {
myMediaPlayer.reset();
try {
myMediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myMediaPlayer.start();
}
}
MediaPlayer mPlayer = MediaPlayer.create(xxx.this, R.raw.xxx);
I have created a package for SoundManagement, with a single class extending MediaPlayer. I was hoping to globally control this variable. Here is my Code:
package soundmanagement;
import android.content.Context;
import android.media.MediaPlayer;
import java.io.IOException;
public class MusicManager extends MediaPlayer {
public static MediaPlayer mediaPlayer = new MediaPlayer();
public void MusicManager() {
}
public static MediaPlayer create(Context context, int musicID) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
mediaPlayer.create(context, musicID);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
return mediaPlayer.create(context, musicID);
}
public void prepare() {
try {
mediaPlayer.prepare();
super.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
if (mediaPlayer != null) {
mediaPlayer.start();
}
super.start();
}
public void pause() {
mediaPlayer.pause();
super.pause();
}
public void stop() {
super.stop();
mediaPlayer.release();
}
public void release() {
mediaPlayer.release();
super.release();
}
public boolean isPlaying(boolean isPlaying) {
super.isPlaying();
return isPlaying;
}
public void setLooping(boolean setLoop) {
mediaPlayer.setLooping(setLoop);
super.setLooping(setLoop);
}
}
And in my MainActivity.class, in onCreate(), all I do is write this code in the onCreate():
MusicManager.mediaPlayer.create(MainActivity.this, R.raw.riseofcc);
MusicManager.mediaPlayer.start();
The application compiles and runs fine, just no music playing once it starts up.
You're taking a curious approach to the MediaPlayer, but one thing that jumps out at me is this:
public static MediaPlayer create(Context context, int musicID) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
mediaPlayer.create(context, musicID);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
return mediaPlayer.create(context, musicID);
}
You call mediaPlayer.create(), then .prepare(), then create(...) again?
Also, create is a static method, so it should be called as MediaPlayer.create and you should hold the reference to it. When you're calling prepare(), you're calling prepare() on a MediaPlayer object that hasn't been created.
Edit: If you want to keep this method, revise it accordingly:
public static MediaPlayer create(Context context, int musicID) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(context, musicID);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
return mediaPlayer;
}
Thread th = new Thread(){
public void run()
{
try{
sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent openMainActivity = new Intent("com.askselva.simple.MENU");
startActivity(openMainActivity);
}
}
};
th.start(); //Error -1
Error 1 : Syntax error on token "start", Identifier expected after
this token
The thing is, you shouldn't have your th.start() outside your class methods. You can't put it randomly inside your class like that.
Your th.start(); statement should be present in some method in your Activity class. You can't just have that lying around somewhere in the activity.
In your case, it could go in the OnCreate() method, but the thread creation must be done before you start the thread there.
try this
package com.askselva.simple;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle selvaLovesKumar) {
super.onCreate(selvaLovesKumar);
setContentView(R.layout.splash);
ourSong=MediaPlayer.create(Splash.this, R.raw.airtel);
ourSong.start();
Thread th = new Thread(){
public void run()
{
try{
sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent openMainActivity = new Intent("com.askselva.simple.MENU");
startActivity(openMainActivity);
}
}
};
th.start();
}
#Override
protected void onPause() {
super.onPause();
finish();
ourSong.release();
}
}
This may help u...
in onCreate Method
Thread currentThread = new Thread(this);
currentThread.start();
after on create
public void run() {
try {
Thread.sleep(4000);
threadHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
//don't forget to deal with the Exception !!!!!
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Intent in = new Intent(getApplicationContext(),****.class);
startActivity(in);
}
};
you can also try this :)
package com.askselva.simple;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity{
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle selvaLovesKumar){
// TODO Auto-generated method stub
super.onCreate(selvaLovesKumar);
setContentView(R.layout.splash);
ourSong=MediaPlayer.create(Splash.this, R.raw.airtel);
ourSong.start();
new Thread(new Runnable()){
public void run(){
try{
sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent openMainActivity = new Intent("com.askselva.simple.MENU");
startActivity(openMainActivity);
}
}
}.start();
}
#Override
protected void onPause(){
// TODO Auto-generated method stub
super.onPause();
finish();
ourSong.release();
}
}
I've been working on this for a while, trying to get this tutorial to work (http://united-coders.com/nico-heid/an-android-seekbar-for-your-mediaplayer/), but I haven't had any luck. The audio playback works perfect, but the SeekBar doesn't move.
package com.example.playingaudio;
import java.io.FileInputStream;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
public class MainActivity extends Activity implements Runnable {
private MediaPlayer mediaPlayer;
private SeekBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
progress = (SeekBar) findViewById(R.id.seekBar1);
}
public void playButton(View view) {
try {
playRecording();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void playRecording() throws Exception {
final MediaPlayer mediaPlayer = new MediaPlayer();
FileInputStream fileStream = new FileInputStream(
"/sdcard/Download/mySong.mp3");
mediaPlayer.setDataSource(fileStream.getFD());
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
run();
}
private void ditchMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void run() {
// mp is your MediaPlayer
// progress is your ProgressBar
int currentPosition = 0;
int total = mediaPlayer.getDuration();
progress.setMax(total);
while (mediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progress.setProgress(currentPosition);
}
}
}
Try changing this line
final MediaPlayer mediaPlayer = new MediaPlayer();
To, this line
mediaPlayer = new MediaPlayer();
The reason is you already have a class variable mediaPlayer declared and why are you declaring the local variable again with the same name.
The reason your bar is not updating is because you aren't giving it a chance to. You have a constant loop on your UI thread that consists mostly of sleep(). You can't do that and expect the UI to update.
If you look at that tutorial more closely, you'll see that they don't call runOnUiThread(). In fact, at the bottom there is a link back to SO, which shows a bit more of the code involved. There's just a new Thread created, and start() is run. Nothing too tricky.
Example:
(call this method after mediaPlayer.start()):
private void createProgressThread() {
progressUpdater = new Runnable() {
#Override
public void run() {
//...
//...
}
};
Thread thread = new Thread(progressUpdater);
thread.start();
}