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
Related
Everybody,
I'm trying to record audio.
The audio is record perfectly when record button is clicked.
I try to stop the record and the app crashing immediately after the stop button is clicked.
Can you please help me on fixing this code so i could continue building my project.
Here's part of the code:
public class window2 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner spinner;//choice between record and Speech-2-text.
Button play,stop,record;//record, stop and replay buttons.
String outputFile;//the record file.
MediaRecorder myAudioRecorder;//the record method.
int reRecord = 0;//reRecord value.
int pathVal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_window2);
spinner = findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);//upon change between record and S2T.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor edit = sharedPreferences.edit();
if( sharedPreferences.getInt("pathVal",0) == 0)
edit.putInt("pathVal",1);
else {
pathVal = sharedPreferences.getInt("pathVal", pathVal);
edit.putInt("pathVal",pathVal+1);
}
pathVal = sharedPreferences.getInt("pathVal", 0);
edit.commit();
//3 buttons for record,stop and replay.
play = findViewById(R.id.button14);
stop = findViewById(R.id.button13);
record = findViewById(R.id.button11);
//to immune issues that may start if the buttons are enabled.
stop.setEnabled(false);
play.setEnabled(false);
//the file of recording.
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+pathVal+".3gp";
//record settings.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
//record button click.
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play.setEnabled(false);
try{
//if we want to re record.
if(reRecord == 1)
{
//we build the settings again.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
//prepare and start methods.
myAudioRecorder.prepare();
myAudioRecorder.start();
}catch (IllegalStateException ise) {
//something
}catch (IOException ioe){
//something
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(window2.this, "Recording...", Toast.LENGTH_SHORT).show();
}
});
//stop button click.
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
myAudioRecorder.reset();
reRecord = 1;
myAudioRecorder = null;
record.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(window2.this, "Recorded!", Toast.LENGTH_SHORT).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(outputFile);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(window2.this, "Playing.", Toast.LENGTH_SHORT).show();
} catch (Exception e){
//something
}
}
});
}
public void OpenWindow4(View view)
{
Spinner spinner = findViewById(R.id.spinner3);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_TEXT",editTextTxt);
intent.putExtra("SPIN_CHOICE",SpinTxt);
startActivity(intent);
}
public void OpenWindow4Speech(View view)
{
Spinner spinner = findViewById(R.id.spinner4);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText2);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_RECORD",outputFile);
intent.putExtra("SPIN_CHOICE",SpinTxt);
intent.putExtra("THE_TEXT",editTextTxt);
startActivity(intent);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if (item.equals("S2T"))
{
Intent intent = new Intent(this,windows2B.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
and here is the logcat:
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: prepare
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: start
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: start failed: -38
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Do partial code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: After code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Increasing code cache capacity to 512KB
01-13 08:42:27.759 1031-1038/com.example.simplenigal.prealphabuilt I/art: Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
01-13 08:42:31.382 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
01-13 08:42:31.452 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: stop
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: stop called in an invalid state: 0
01-13 08:42:31.463 1031-1031/com.example.simplenigal.prealphabuilt D/AndroidRuntime: Shutting down VM
01-13 08:42:31.468 1031-1031/com.example.simplenigal.prealphabuilt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.simplenigal.prealphabuilt, PID: 1031
java.lang.IllegalStateException
at android.media.MediaRecorder.native_stop(Native Method)
at android.media.MediaRecorder.stop(MediaRecorder.java:896)
at com.example.simplenigal.prealphabuilt.window2$2.onClick(window2.java:102)
at android.view.View.performClick(View.java:5624)
at android.view.View$PerformClick.run(View.java:22441)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6316)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
thanks to every one who paying attention and helping.
Still looking for help
I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
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:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
I have been developing a weather app through Treehouse and unfortunately no one has been able to help me fix this perticular error.
For some reason no weather data is retrieved on the app. I signed up through forecast IO to get the weather data to the app but nothing appears and the app crashes.
I use my phone as an emulator but I receive no errors in the log. Only when I use the Android Studio emulator do I receive an error in the logcat. Any suggestions ?
Stormy app on gitHub
Github
MainActivity.java file
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
#InjectView(R.id.humidityValue) TextView mHumidityValue;
#InjectView(R.id.precipValue) TextView mPrecipValue;
#InjectView(R.id.summaryLabel) TextView mSummaryLabel;
#InjectView(R.id.iconImageView) ImageView mIconImageView;
#InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
final double latitude = 38.627;
final double longitude = -90.199;
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "8ec5f1674002ab5081cad28e9be10ced";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if(isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
toggleRefresh();
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, response.body().string());
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
updateDisplay();
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (JSONException e) {
Log.e(TAG, "Exception caught:", e);
}
}
});
}
else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mRefreshImageView.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
mTimeLabel.setText("At" + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON:" + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getLong("time"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return new CurrentWeather();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
"PropertyFetcher: AdbCommandRejectedException getting properties for
device 0043d8b5c84ed1f5: device unauthorized.
Please check the confirmation dialog on your device."
Error log
02-10 14:17:31.130 52-52/? I/qemu-props﹕ received: qemu.hw.mainkeys=0
02-10 14:17:33.180 56-56/? I/SurfaceFlinger﹕ SurfaceFlinger's main thread ready to run. Initializing graphics H/W...
02-10 14:18:51.060 624-624/? D/AndroidRuntime﹕ Calling main entry com.android.commands.pm.Pm
02-10 14:19:01.630 548-548/com.android.launcher I/Choreographer﹕ Skipped 346 frames! The application may be doing too much work on its main thread.
02-10 14:19:02.750 437-437/? I/Choreographer﹕ Skipped 1210 frames! The application may be doing too much work on its main thread.
02-10 14:19:04.920 386-386/system_process W/BroadcastQueue﹕ Failure sending broadcast Intent { act=android.intent.action.TIME_TICK flg=0x50000014
(has extras) } android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.app.ApplicationThreadProxy.scheduleRegisteredReceiver(ApplicationThreadNative.java:1059)
at com.android.server.am.BroadcastQueue.performReceiveLocked(BroadcastQueue.java:421)
at com.android.server.am.BroadcastQueue.deliverToRegisteredReceiverLocked(BroadcastQueue.java:507)
at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:714)
at com.android.server.am.ActivityManagerService.finishReceiver(ActivityManagerService.java:13807)
at android.content.BroadcastReceiver$PendingResult.sendFinished(BroadcastReceiver.java:419)
at android.content.BroadcastReceiver$PendingResult.finish(BroadcastReceiver.java:395)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:785)
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 com.android.server.ServerThread.initAndLoop(SystemServer.java:1093)
at com.android.server.SystemServer.main(SystemServer.java:1179)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
02-10 14:19:08.800 386-386/system_process I/Choreographer﹕ Skipped 34 frames! The application may be doing too much work on its main thread.
02-10 14:19:19.860 548-548/com.android.launcher I/Choreographer﹕ Skipped 1089 frames! The application may be doing too much work on its main thread.
02-10 14:19:23.320 718-718/com.android.systemui I/Choreographer﹕ Skipped 679 frames! The application may be doing too much work on its main thread.
02-10 14:19:25.100 718-718/com.android.systemui I/Choreographer﹕ Skipped 106 frames! The application may be doing too much work on its main thread.
02-10 14:19:27.700 718-718/com.android.systemui I/Choreographer﹕ Skipped 154 frames! The application may be doing too much work on its main thread.
02-10 14:19:30.720 548-548/com.android.launcher I/Choreographer﹕ Skipped 61 frames! The application may be doing too much work on its main thread.
02-10 14:19:57.300 893-893/? D/AndroidRuntime﹕ Calling main entry com.android.commands.am.Am
02-10 14:19:57.400 386-398/system_process I/ActivityManager﹕ START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=aurielvilaire.com.stormy/.MainActivity} from pid 893
02-10 14:19:57.890 386-714/system_process I/ActivityManager﹕ Start proc aurielvilaire.com.stormy for activity aurielvilaire.com.stormy/.MainActivity: pid=928 uid=10054 gids={50054, 3003}
02-10 14:20:00.640 928-928/aurielvilaire.com.stormy D/MainActivity﹕ Main UI code is running!
02-10 14:20:02.170 386-400/system_process I/ActivityManager﹕ Displayed aurielvilaire.com.stormy/.MainActivity: +4s339ms
02-10 14:20:05.540 928-943/aurielvilaire.com.stormy D/MainActivity﹕ 1:20 PM
02-10 14:20:05.600 928-943/aurielvilaire.com.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher Process: aurielvilaire.com.stormy, PID: 928 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
at android.view.View.requestLayout(View.java:16431)
at android.widget.TextView.checkForRelayout(TextView.java:6600)
at android.widget.TextView.setText(TextView.java:3813)
at android.widget.TextView.setText(TextView.java:3671)
at android.widget.TextView.setText(TextView.java:3646)
at aurielvilaire.com.stormy.MainActivity.updateDisplay(MainActivity.java:154)
at aurielvilaire.com.stormy.MainActivity.access$500(MainActivity.java:31)
at aurielvilaire.com.stormy.MainActivity$2.onResponse(MainActivity.java:122)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:162)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
02-10 14:20:05.650 386-397/system_process W/ActivityManager﹕ Force finishing activity aurielvilaire.com.stormy/.MainActivity
02-10 14:20:05.710 386-414/system_process W/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
02-10 14:20:05.710 386-414/system_process E/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
02-10 14:20:05.720 386-606/system_process W/InputDispatcher﹕ Attempted to unregister already unregistered input channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)'
02-10 14:20:05.720 386-606/system_process I/WindowState﹕ WIN DEATH: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:05.960 386-397/system_process I/WindowManager﹕ Screenshot max retries 4 of Token{b2051338 ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity t2 f}} appWin=Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity EXITING} drawState=4
02-10 14:20:07.260 548-548/com.android.launcher I/Choreographer﹕ Skipped 59 frames! The application may be doing too much work on its main thread.
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ This window was lost: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ mDisplayId=0 mSession=Session{b210e748 928:u0a10054}
mClient=android.os.BinderProxy#b2116298 mOwnerUid=10054
mShowToOwnerOnly=true package=aurielvilaire.com.stormy appop=NONE
mAttrs=WM.LayoutParams{(0,0)(fillxfill) sim=#120 ty=1 fl=#1810100
pfl=0x8 wanim=0x10302a1} Requested w=1080 h=1776 mLayoutSeq=71
mBaseLayer=21000 mSubLayer=0 mAnimLayer=21000+0=21000 mLastLayer=0
mToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mRootToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mAppToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mViewVisibility=0x0 mHaveFrame=true mObscured=true mSeq=0
mSystemUiVisibility=0x0 mPolicyVisibility=false
mPolicyVisibilityAfterAnim=false mAppOpVisibility=true
mAttachedHidden=false mGivenContentInsets=[0,0][0,0]
mGivenVisibleInsets=[0,0][0,0] mConfiguration={1.0 310mcc260mnc en_US
ldltr sw360dp w360dp h567dp 480dpi nrml port finger qwerty/v/v -nav/h
s.5} mHasSurface=true mShownFrame=[0.0,0.0][1080.0,1776.0]
isReadyForDisplay()=false mFrame=[0,0][1080,1776]
last=[0,0][1080,1776] mSystemDecorRect=[0,0][1080,1776]
last=[0,0][1080,1776] Frames: containing=[0,0][1080,1776]
parent=[0,0][1080,1776] display=[0,0][1080,1776]
overscan=[0,0][1080,1920] content=[0,75][1080,1776]
visible=[0,75][1080,1776] decor=[0,0][1080,1920] Cur insets:
overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0] Lst
insets: overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0]
WindowStateAnimator{b20db3d0
aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}:
mSurface=Surface(name=aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity)
mDrawState=HAS_DRAWN mLastHidden=true Surface: shown=false layer=21005
alpha=0.0 rect=(0.0,0.0) 1080.0 x 1776.0 mShownAlpha=1.0 mAlpha=1.0
mLastAlpha=-1.0 mGlobalScale=1.0 mDsDx=1.0 mDtDx=0.0 mDsDy=0.0
mDtDy=1.0 mExiting=false mRemoveOnExit=false mDestroying=true
mRemoved=false
02-10 14:20:52.610 386-606/system_process I/ActivityManager﹕ Start proc com.android.email for broadcast com.android.email/.service.EmailBroadcastReceiver: pid=1049 uid=10024 gids={50024, 3003, 1028, 1015}
02-10 14:20:53.400 1049-1063/com.android.email D/ActivityThread﹕ Loading provider com.android.email.provider;com.android.email.notifier: com.android.email.provider.EmailProvider
02-10 14:20:58.452 386-583/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.522 1049-1103/com.android.email I/Email﹕Observing account changes for notifications
02-10 14:20:58.622 386-432/system_process I/ActivityManager﹕ Start proc com.android.exchange for service com.android.exchange/.service.EmailSyncAdapterService: pid=1104 uid=10025 gids={50025, 3003, 1028, 1015}
02-10 14:20:58.622 386-607/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.882 1049-1065/com.android.email D/dalvikvm﹕ GC_FOR_ALLOC freed 313K, 16% free 3359K/3960K, paused 231ms, total 254ms
02-10 14:21:49.352 718-718/com.android.systemui I/Choreographer﹕ Skipped 32 frames! The application may be doing too much work on its main thread.
After reading through that and looking at your code, I believe the main culprit here is that you are doing to much on the main thread. You should use the android AsyncTask to run especially network connections on a separate thread. For example you might use:
private class DownloadForecast extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
getForecast(); //run all your network intensive methods
return response;
}
#Override
protected void onPostExecute(String result) {
//update all your UI stuff.
}
Can't seem to correctly intent the code. But thats what you should use. Good luck.
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);
}
}
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.