I'm working on a app that performs a function once I shake the phone. For this I created a class named ShakeListener. My app works perfectly like its supposed to when I open it. When I open the app and press the back button and go to my home screen and shake the phone it turns on the flash(like it's supposed) but when I open the app again it crashes. I don't know why this is happening
My main activity is
public class MainActivity extends ActionBarActivity {
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean stopshake = getprefs.getBoolean("checkbox", true);
if (stopshake) {
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
if (!isFlashOn && mShaker != null ) {
getCamera();
turnOnFlash();
} else {
turnOffFlash();
}
}
});
} else {
if (mShaker != null) {
mShaker.setOnShakeListener(null);
mShaker = null;
}
}
}
private ToggleButton togle;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
private ShakeListener mShaker;
MediaPlayer mp;
ImageView anime;
int p=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anime = (ImageView) findViewById(R.id.Animation);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish(); }
});
alert.show();
return;}
getCamera();
togle = (ToggleButton) findViewById(R.id.ToggleButton01);
togle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean checked = ((ToggleButton) v).isChecked();
if (checked){
turnOffFlash();
}
else{
getCamera();
turnOnFlash();
}
}
});
}
private void getCamera() {
// TODO Auto-generated method stub
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
} }
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
getCamera();
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
anime.setImageResource(R.drawable.anim);
anime.post(new Runnable() {
@Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) anime.getDrawable();
frameAnimation.start();
}
});
// changing button/switch image
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
isFlashOn = false;
anime.setImageResource(R.drawable.off);
// changing button/switch image
}
}
private void playSound() {
// TODO Auto-generated method stub
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.off1);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.on1);
}
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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.
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.action_settings:
Intent intent = new Intent(MainActivity.this, Prefsetting.class);
startActivity(intent);
break;
case R.id.about:
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("This is an alert with no consequence");
dlgAlert.setTitle("App Title");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
break;
}
return true;
}
}
My logcat shows
08-23 04:31:53.205: D/ShakeListener(11990): ShakeListener invoked----> 08-23 04:31:53.207: D/ShakeListener(11990): ShakeListener setOnShakeListener invoked----> 08-23 04:31:53.312: D/AndroidRuntime(11990): Shutting down VM 08-23 04:31:53.314: E/AndroidRuntime(11990): FATAL EXCEPTION: main 08-23 04:31:53.314: E/AndroidRuntime(11990): Process: com.shakylight, PID: 11990 08-23 04:31:53.314: E/AndroidRuntime(11990): java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable cannot be cast to android.graphics.drawable.AnimationDrawable 08-23 04:31:53.314: E/AndroidRuntime(11990): at com.shakylight.MainActivity$4.run(MainActivity.java:145) 08-23 04:31:53.314: E/AndroidRuntime(11990): at android.os.Handler.handleCallback(Handler.java:739) 08-23 04:31:53.314: E/AndroidRuntime(11990): at android.os.Handler.dispatchMessage(Handler.java:95) 08-23 04:31:53.314: E/AndroidRuntime(11990): at android.os.Looper.loop(Looper.java:135) 08-23 04:31:53.314: E/AndroidRuntime(11990): at android.app.ActivityThread.main(ActivityThread.java:5254) 08-23 04:31:53.314: E/AndroidRuntime(11990): at java.lang.reflect.Method.invoke(Native Method) 08-23 04:31:53.314: E/AndroidRuntime(11990): at java.lang.reflect.Method.invoke(Method.java:372) 08-23 04:31:53.314: E/AndroidRuntime(11990): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 08-23 04:31:53.314: E/AndroidRuntime(11990): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
DISCLAIMER: I cannot test what I advise you to try here but it might work just fine. In any case, you can let me know in the comments.
So the error is coming from this line:
AnimationDrawable frameAnimation = (AnimationDrawable) anime.getDrawable();
I'm no expert and the documentation doesn't help. Android documentation example is the following: (see here: http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html)
AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
However, a thorough search on SO (here="Class Cast Exception" when trying to set image frames to background) gave me this where the solution is apparently to do the following (contrary to the logic of the documentation):
Drawable drawable = getResources().getDrawable(R.drawable.<your_animation_xml_file_name>)