Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android/Java understanding when I'm able to use/overwrite variable

Tags:

java

android

I have a variable that I get from shared preferences when I load the app.

I first initialize the variable

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final String camera_type = booth_preferences.getString("camera_key", "back");

Then later down the line, I get that variable and do something with it

if(camera_type.equals("front")){
        //do something
} else if(camera_type.equals("ext")){
        //do something
} else {
        //do something
}

Now, directly after that if statement, I have an onclick listener that is supposed to change and update that preference.

camera_button_front.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        //do something
        edit_preferences.putString(camera_key, "front").commit();
    }
});
camera_button_back.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        //do something
        edit_preferences.putString(camera_key, "back").commit();
    }
});
camera_button_ext.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        //do something
        edit_preferences.putString(camera_key, "ext").commit();
    }
});

But when I try to change the variable camera_type I get errors stating "cannot assign a value to final variable 'camera_type'".

camera_button_ext.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        //do something
        edit_preferences.putString(camera_key, "ext").commit();
        camera_type = "ext";
    }
});

I've ever reinstated the variable after the onclick hoping it would over write the variable completely.

camera_button_ext.setOnClickListener(new View.OnClickListener() {
    String camera_type;
    public void onClick(View v) {
        //do something
        edit_preferences.putString(camera_key, "ext").commit();
        camera_type = "ext";
    }
});

If I were to remove the final then I'm not able to use the variable in the if statement.

I'm new to Java, so this should be a simple answer, I'm just not sure which combination of wrong I'm doing.

like image 358
ntgCleaner Avatar asked Mar 12 '26 22:03

ntgCleaner


1 Answers

You should make your variable a non-final field. Then you can use it within the onClick (and all other methods of the class) and also reassign it as you wish.

private String camera_type; // member variable

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    camera_type = booth_preferences.getString("camera_key", "back");
like image 83
OneCricketeer Avatar answered Mar 15 '26 11:03

OneCricketeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!