create account

Android: SharedPreferences to save Data by imjason

View this thread on: hive.blogpeakd.comecency.com
· @imjason · (edited)
$0.16
Android: SharedPreferences to save Data
![](https://cdn.steemitimages.com/DQmfRo8oeyMB7XfrWPCWTPd9bUgPkrfTLW1ATPQuLrKxR54/image.png)

A view will automatically save its instance state if it has a unique id, but if you press back the data will still be destroyed. SharedPreferences are used to store key-value pairs for our apps. Typical uses are to save the user's name, keep track of what theme the user prefers, store a counter of how many times the user signed on, or keep track of the high score.

<B>First, start off by declaring a constant for the file name. Then declare a constant for the key we'll require:</B>

private static final String PREFS_FILE = "com.company.preferences";   //.preferences at the end is standard naming convention

private static final String KEY_CHECKBOX = "key_checkbox";

<B>Second, declare SharedPreferences and an Editor field.</B>

private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;

<B>Third, initialize mSharedPreferences and mEditor in onCreate method.<B>

mSharedPreferences = getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();

<B>Forth, Override onPause method. Save the value in a Boolean and apply</B>

mEditor.putBoolean(KEY_CHECKBOX, mCheckBox.isChecked());
mEditor.apply();

<B>Lastly, Retrieve the saved value in onCreate and set the state of the CheckBox</B>

Boolean isCheckBoxChecked = mSharedPreferences.getBoolean(KEY_CHECKBOX, false);
mCheckBox.setChecked(isCheckBoxChecked);

<B>Example 1: uses a checkbox </B>

import android.view.View;
import android.os.Bundle;

public class MainActivity extends Activity {
    
  private static final String PREFS_FILE= "com.company.preferences";
  private static final String KEY_CHECKBOX= "key_checkbox";
  
  private SharedPreferences mSharedPreferences;
  private SharedPreferences.Editor mEditor;
  public CheckBox mCheckBox;

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

    mCheckBox = (CheckBox) findViewById(R.id.checkBox);
    mSharedPreferences = getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
    mEditor = mSharedPreferences.edit();

    Boolean isCheckBoxChecked = mSharedPreferences.getBoolean(KEY_CHECKBOX, false);
    mCheckBox.setChecked(isCheckBoxChecked);
  }
  @Override
  protected void onPause(){
    super.onPause();
    
    mEditor.putBoolean(KEY_CHECKBOX, mCheckBox.isChecked());
    mEditor.apply();
  }
}
 



<B>Example 2: uses an editText</B>

public class MainActivity extends AppCompatActivity{
    private static final String PREFS_FILE = "com.company.preferences";
    private static final String KEY_EDIITTEXT = "key_edittext";
    private SharedPreferences.Editor mEditor;
    private SharedPreferences mSharedPreferences;
    private EditText mEditText;

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

        mEditText = (EditText) findViewById(R.id.editText);
        mSharedPreferences = getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
        mEditor = mSharedPrefernces.edit();

        String editTextString = mSharedPreferences.getString(KEY_EDITTEXT, ""); //pass in key and empty string for default when string isn't found
        mEditText.setText(editTextString);   //update our editText
    }

    @Override
    protected void onPause(){
        super.onPause();
        
        mEditor.putString(KEY_EDITTEXT, mEditText.getText().toString());
        mEditor.apply();
    }
}

To clear to default values, you can use the clear method of a sharedPreferences editor Object. Also, can use the remove() and pass in a key to remove just one value (don't forget apply() to update value).
👍  , ,
properties (23)
authorimjason
permlinkandroid-sharedpreferences-to-save-data
categorysteem
json_metadata{"tags":["steem","technology","android","programming","life"],"users":["override"],"image":["https://cdn.steemitimages.com/DQmfRo8oeyMB7XfrWPCWTPd9bUgPkrfTLW1ATPQuLrKxR54/image.png"],"app":"steemit/0.1","format":"markdown"}
created2018-07-27 08:14:03
last_update2018-07-27 19:44:00
depth0
children2
last_payout2018-08-03 08:14:03
cashout_time1969-12-31 23:59:59
total_payout_value0.132 HBD
curator_payout_value0.029 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length3,806
author_reputation73,915,460,065
root_title"Android: SharedPreferences to save Data"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,131,703
net_rshares87,902,208,080
author_curate_reward""
vote details (3)
@steemitboard ·
Congratulations @imjason! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

[![](https://steemitimages.com/70x70/http://steemitboard.com/notifications/firstpayout.png)](http://steemitboard.com/@imjason) You got your First payout
[![](https://steemitimages.com/70x80/http://steemitboard.com/notifications/payout.png)](http://steemitboard.com/@imjason) Award for the total payout received

<sub>_Click on the badge to view your Board of Honor._</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>


To support your work, I also upvoted your post!


> Do you like [SteemitBoard's project](https://steemit.com/@steemitboard)? Then **[Vote for its witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1)** and **get one more award**!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-imjason-20180727t122900000z
categorysteem
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2018-07-27 12:29:00
last_update2018-07-27 12:29:00
depth1
children0
last_payout2018-08-03 12:29:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length875
author_reputation38,975,615,169,260
root_title"Android: SharedPreferences to save Data"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id66,152,794
net_rshares0
@steemitboard ·
Congratulations @imjason! You received a personal award!

<table><tr><td>https://steemitimages.com/70x70/http://steemitboard.com/@imjason/birthday2.png</td><td>Happy Birthday! - You are on the Steem blockchain for 2 years!</td></tr></table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@imjason) and compare to others on the [Steem Ranking](https://steemitboard.com/ranking/index.php?name=imjason)_</sub>


###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-imjason-20190617t074902000z
categorysteem
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2019-06-17 07:49:03
last_update2019-06-17 07:49:03
depth1
children0
last_payout2019-06-24 07:49:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length616
author_reputation38,975,615,169,260
root_title"Android: SharedPreferences to save Data"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id86,766,319
net_rshares0