Reputation: 379
I have looked around online for similar threads, but none have been helpful.
I'm trying to do the SIMPLE task of making onClick button sounds. I worked for hours on end trying to get the code right, and as soon as it looks like it's going to work, it won't even run.
It says, "Unfortunately, Attempt has stopped." and my LogCat file opens with 200+ error messages that make no sense.
Could you look at my code and tell me what the problem is? Thank you.
package com.example.attempt;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button) findViewById(R.id.muteButton);
button.setOnClickListener(this);
}
AudioManager audioManager =
(AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
public void onClick(View v) {
audioManager.playSoundEffect(SoundEffectConstants.CLICK);
}
}
Upvotes: 0
Views: 168
Reputation: 3064
this
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button) findViewById(R.id.muteButton);
button.setOnClickListener(this);
}
AudioManager audioManager =
(AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
Change it to
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioManager audioManager =
(AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
Button button=(Button) findViewById(R.id.muteButton);
button.setOnClickListener(this);
}
Upvotes: 1
Reputation: 132982
initialize AudioManager
audioManager instance inside onCreate
method as :
AudioManager audioManager; //<<<< declare here...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button) findViewById(R.id.muteButton);
button.setOnClickListener(this);
/// initialize here
audioManager =
(AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
}
Upvotes: 5