MediaPlayer works in Android, but progress does not - java

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();
}

Related

Getting the value from textview

Hello guys I got a code that I do for my project, the code is to get the value of the heartbeat sensor from Arduino to my android phone using Bluetooth. So far it's going well it can send the value to my app without a problem. but the problem now is I want to get the value of it so I can use my algorithm with it, but seems like I got in a pickle now.
Here is the code :
package com.test.aplikasirevisi;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import android.app.Activity;
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.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class MonitoringScreen extends Activity {
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private boolean mIsUserInitiatedDisconnect = false;
private TextView mTxtReceive;
private Button mBtnClearInput;
private ScrollView scrollView;
private CheckBox chkScroll;
private CheckBox chkReceiveText;
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_screen);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
mTxtReceive = (TextView) findViewById(R.id.txtReceive);
chkScroll = (CheckBox) findViewById(R.id.chkScroll);
chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
scrollView = (ScrollView) findViewById(R.id.viewScroll);
mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
mBtnClearInput.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mTxtReceive.setText("");
}
});
}
private class ReadInput implements Runnable{
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
if (chkReceiveText.isChecked()) {
mTxtReceive.post(new Runnable() {
#Override
public void run() {
mTxtReceive.append(strInput);
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
System.out.println(mTxtReceive.getText().toString());
}
if (chkScroll.isChecked()) { // Scroll only if this is checked
scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
#Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
}
});
}
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MonitoringScreen.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
}
What i want is to get the value of mTxtReceive on this :
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
System.out.println(mTxtReceive.getText().toString());
}
I used System.out.println for seeing if i got the value but in the log it didn't show any thing.
So i need you guys wisdom for this any help?
Your view mTextReceive seems to be a TextView and therefore not editable:
private TextView mTxtReceive;
If it's not an EditText (editable) mTxtReceive.getEditableText will return null see docs
and getText should be called instead see docs.
Therefore your condition might always resolve from
if(txtLength > mMaxChars) into if(null > 50000) which is always false (or actually it might even crash before) and therefore your code inside the if-block is never executed
Try:
// recommended for debugging. Check if this is even called and if text length is really longer than max chars
Log.d(TAG, "text length:" + mTxtReceive.getText().length());
int txtLength = mTxtReceive.getText().length();
if(txtLength > mMaxChars){
// not sure what operation you want to do here but leave out for debugging
Log.d(TAG, "text longer than allowed:" + mTxtReceive.getText().toString());
}
Also use Log.d instead of System.out.println since your log might otherwise not be forwarded to Logcat. Also are you sure this block is executed at all? I'd put a Log.d(TAG, "text length:" + mTxtReceive.getText().length()); outside of the condition for debugging purposes. And finally the obvious question would be if the txtLength is even longer than max chars (and that would be quite a long text with 50000 chars). But you can verify that simply with the recommended log outside the block as well.

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.

Trying to get the MediaRecorder to reset and also to continue running when I change to a different class

Currently I am facing three issues:
Getting the MediaRecorder to reset instead of release.
I think i need to create a new instance of the MediaRecorder and release() it as well, but I do not know where.
I want it to keep recording audio until the phone dies and even when the user changes to a different screen (i.e. going to a new class).
I have tried to google this but do not know how to achieve it.
Edit - I figured out how to use SimpleDateFormat!
Edit 2 - Realised I need to create a started service for my 2nd issue.
My code is as follows
Class:
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Drugs extends AppCompatActivity {
WebView myBrowser;
MediaRecorder mRecorder;
private static String audioFilePath;
public boolean isRecording = false;
MediaPlayer mediaPlayer;
public boolean isPlaying = false;
SimpleDateFormat simpledate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drugs);
myBrowser = (WebView) findViewById(R.id.mybrowser);
myBrowser.loadUrl("file:///android_asset/drugs.html");
myBrowser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
Button btndrugslaw = (Button) findViewById(R.id.drugslaw);
btndrugslaw.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intentdruglaw = new Intent(Drugs.this, DrugLaw.class);
startActivity(intentdruglaw);
}
});}
public void RecordButton (View view) {
if(mRecorder == null){
audioFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + simpledate
+ "/myaudio.3gp";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(audioFilePath);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
if (isRecording) {
try{
stopRecording();
isRecording = false;
((Button)view).setText("Start Recording");
}catch(Exception e){
e.printStackTrace();
}
} else {
try{
startRecording();
isRecording = true;
((Button)view).setText("Stop Recording");
}catch(Exception e){
e.printStackTrace();
}
}
}
public void startRecording() throws IllegalStateException, IOException{
mRecorder.prepare();
MediaRecorder mRecorder = new MediaRecorder();
mRecorder.start();
}
public void stopRecording() throws IllegalStateException, IOException{
mRecorder.stop();
mRecorder.reset();
}
public void StartPlaying(View view) throws IllegalStateException, IOException {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(audioFilePath);
}
if (isPlaying) {
try {
stopPlaying();
isPlaying = false;
((Button)view).setText("Play Audio");
} catch (Exception e) {
e.printStackTrace();
}
} else {
try{
startPlaying();
isPlaying = true;
((Button)view).setText("Stop Audio");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void startPlaying() throws IllegalStateException, IOException {
mediaPlayer.prepare();
mediaPlayer.start();
}
public void stopPlaying () throws IllegalStateException, IOException {
mediaPlayer.release();
}
}

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/Java: How to reference from a class to the MainActivity.java

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.

Categories