0

I want to update the changes when I uncheck and check the checkbox in the preference activity but when I press the back button it doesn't work. It only works when I close the activity and then open it

Main activity

public class MainActivity extends ActionBarActivity   {
 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(); 
               }
                  }
        });


    SharedPreferences getprefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean stopshake = getprefs.getBoolean("checkbox", true);
    if (stopshake == true ){

    mShaker = new ShakeListener(this); 
    mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
         public void onShake()
         { if (!isFlashOn) {
             Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();

             getCamera();
         turnOnFlash();
         }
         else{
               turnOffFlash();

               Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();   
         } }
       });
         }


    }

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.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        Intent intent = new Intent(MainActivity.this, Prefsetting.class);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

 }

Preference activity

public class Prefsetting extends PreferenceActivity   {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
  addPreferencesFromResource(R.xml.prefset);

}

  }
Blacklotis
  • 145
  • 1
  • 4
  • 14

2 Answers2

0

From the code snippet it appears that you never actually commit your changes to the SharedPreferences of the application. Somewhere in the code when that boolean is flipped you need to do something like this:

prefs.put("checkbox", currentBooleanState).commit();
andrewdleach
  • 2,458
  • 2
  • 17
  • 25
  • This can't be true, as when he restarts his app the changes take effect. Also, with `PreferenceActivity` there is no need to manually commit these changes to `SharedPreferences`. – PPartisan Aug 20 '15 at 22:46
  • @PPartisan is right, it works okay but the only problem it gives is when it doesn't refresh after I move back from the settings activity – Blacklotis Aug 21 '15 at 00:02
0

You access SharedPreferences in the onCreate() of your MainActivity, which is only called when that activity is created from scratch (i.e. when you first start your app). As you (presumably) navigate to and from your Prefsetting Activity fairly quickly, MainActivity is likely only in a paused or stopped state when it is resumed. Take a look at the diagram here to see what happens to Activity classes as they move into and out of the foreground.

You have a couple of options. Either place this:

@Override
public void onResume() {
    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) {
                    Toast.makeText(MainActivity.this, "On" , Toast.LENGTH_SHORT).show();
                    getCamera();
                    turnOnFlash();
                } else {
                    turnOffFlash();
                    Toast.makeText(MainActivity.this, "Off" , Toast.LENGTH_SHORT).show();   
                }
            }
        });
    } else {
        if (mShaker != null) {
            mShaker.setOnShakeListener(null);
            mShaker = null;
        }
    }         
}

Into somewhere like onResume().

Or, use an EventBus like LocalBrodcastManager to update your Preferences when onPause() is called in your PreferenceActivity.

Community
  • 1
  • 1
PPartisan
  • 8,173
  • 4
  • 29
  • 48
  • so I should place it on the onresume and delete it from my code(oncreate)? If I do that then it my shake function will not work and if I place it in my on create and my on resume then it works but doesn't work right – Blacklotis Aug 20 '15 at 23:16
  • @user2435339 I'm not familiar with `ShakeListener`, is it a class you got from a Library? At any rate, I think the problem is to do with `if (stopShake)...` just below your `SharedPreferences`. There needs to be an `else` so that your "ShakeListener" is removed if it is unselected in your `PreferenceActivity`. Try the code above. You should be able to remove it from `onCreate()` and move the above into `onResume()` too. – PPartisan Aug 20 '15 at 23:27
  • ShakeListener is a class I made that contains the shake/movement calibrations. – Blacklotis Aug 20 '15 at 23:56
  • @user2435339 Fair enough - has my edit resolved the problem? – PPartisan Aug 21 '15 at 00:09
  • Yes I tied your edit and it solved the problem, now when I uncheck it stops and updates but it created another problem. Now when I check the checkbox and go back to my home and open the app again(without killing it) it stops working and it says "Unfortunately app stopped" – Blacklotis Aug 21 '15 at 00:13
  • I didn't delete my code from on create BTW I just added your edited code to onresume – Blacklotis Aug 21 '15 at 00:14
  • @user2435339 Please try removing the code transferred to onResume from onCreate, and run your app again. If that doesn't work, I would recommend opening a new question, as this sounds like a separate, unrelated issue. – PPartisan Aug 21 '15 at 00:19
  • 1
    Thank you so much for your help yesterday! It means a lot – Blacklotis Aug 21 '15 at 15:03
  • @user2435339 No problem :) – PPartisan Aug 21 '15 at 15:06