Android – SharedPreference

Pocket
LINEで送る

参考:
基本的なSharedPreferencesの使い方
SharedPreferencesの使い方(基礎編)

サンプルコード

public class MainActivity extends AppCompatActivity{
    private SharedPreferences data;
    private SharedPreferences.Editor editor;
    private Button btn_up, btn_show;
    private TextView txt;
    private Integer cnt;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        data = getSharedPreferences("DataSave", Context.MODE_PRIVATE);
        editor = data.edit();
        cnt = getCount();
        txt = (TextView)findViewById(R.id.txt_count);
        showCount();

        btn_up = (Button)findViewById(R.id.btn_up);
        btn_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cnt += 1;
                saveCount();
            }
        });

        btn_show = (Button)findViewById(R.id.btn_show);
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCount();
            }
        });
    }

    private void saveCount() {
        editor.putInt("count", cnt);
        editor.apply();
    }

    private Integer getCount() {
        return data.getInt("count", 0);
    }

    private void showCount() {
        txt.setText(String.valueOf(cnt));
    }

}
Pocket
LINEで送る

コメントください