Search code examples
androidapplication-settingssavechangespermanent

Save my App's settings permanently


I have a little program(Android APP), When I change the ImageButton's image with a Dialog method, Is there any way to save these changes/settings even after closing my application, I tried to use SharedPreferences, but I do not understand how to do, exist any solution to save my setting?? Thanks!

I post my code:

 import android.widget.Button;
 import android.widget.ImageButton;
 import android.widget.ImageView;
 import android.widget.TextView;
 import android.app.Activity;
 import android.app.Dialog;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;


public class MainActivity extends Activity {

private ImageButton buttonClick;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonClick = (ImageButton) findViewById(R.id.imageButton1);
    buttonClick.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {


            final Dialog dialog = new Dialog(MainActivity.this);

            dialog.setContentView(R.layout.dialog); 

            dialog.setTitle("ChangeIcon");


            TextView text = (TextView) dialog.findViewById(R.id.textDialog);
            text.setText("Choose the element concerned ");


           ImageView image = (ImageView) dialog.findViewById(R.id.imageDialog);
           image.setImageResource(R.drawable.default);

            dialog.show();

            Button declineButton = (Button) dialog.findViewById(R.id.buttonGas);

            declineButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    buttonClick.setImageResource(R.drawable.first_possible_choice);
                   dialog.dismiss(); 
                    } });

            Button secondo = (Button)dialog.findViewById(R.id.buttonFinestra);
            secondo.setOnClickListener(new OnClickListener(){

                @Override
                public void onClick(View v){buttonClick.setImageResource(R.drawable.second_possible choice);
                    dialog.dismiss();
                }

            });
        }
    });
} }

Solution

  • Use SharedPreferences to persist changes even after your App is closed.
    Save resource image path to a key in SharedPrefernces. Use it at the image load time(when onCreate() gets called).

    SharedPreferences sharedPreferences = getSharedPreferences("Name", <Mode>);
    int imageResource = sharedPreferences.getInt("KEY_NAME", <default value>);
    image.setImageResource(imageResource);
    

    On Button click, save the changes in SharedPreferences:

    SharedPreferences.Editor spEditor = sharedPreferences.edit();
    spEditor.putInt("KEY_NAME", <image resource>).commit();