• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Why does my simple app crash

Hi all

Noob here with hopefully a simple question.

Below is a simple app with 3 buttons. The first button displays a message. The second button displays an image. The third button vibrates the phone.

It works fine until the app is paused. Sometimes it pause fine then starts fine but most of the time it says app stopped working and crashes. It also plays an mp3 in the background at startup.

Any help getting it to not crash after pausing would be greatly appreciated.

Thanks

Code:
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    MediaPlayer mySound;
    Vibrator vibe;

    @Override
    protected void onPause() {
        super.onPause();
        mySound.release();
        vibe.cancel();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mySound = MediaPlayer.create(this, R.raw.song);
        mySound.start();
    }

    public void OnClick1(View v){
        TextView view = (TextView)findViewById((R.id.textView1));
        view.setText("I Love You");
    }

    public void OnClick2(View v){
        ImageView hearts = (ImageView)findViewById((R.id.imageView1));
        hearts.setVisibility(View.VISIBLE);
    }

    public void OnClick3(View v){

        vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibe.vibrate(80000);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
 
Back
Top Bottom