Advertisement
irobust

Android Shared Preference

Sep 15th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. 1. Application
  2. public class BaseApplication extends Application {
  3.  
  4. @Override
  5. public void onCreate() {
  6. super.onCreate();
  7.  
  8. SharedPreferences pref = getSharedPreferences("settings", MODE_PRIVATE);
  9. SharedPreferences.Editor editor = pref.edit();
  10.  
  11. editor.putString("display-name", "John Doe");
  12. editor.putBoolean("safe-mode", true);
  13.  
  14. editor.apply();
  15. }
  16. }
  17.  
  18. 2. Activity
  19. @Override
  20. protected void onCreate(Bundle savedInstanceState) {
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.activity_main);
  23.  
  24. ButterKnife.bind(this);
  25. }
  26.  
  27. @BindView(R.id.tvShowPreference) TextView tvShowPreference;
  28.  
  29. @OnClick(R.id.btnGetPref)
  30. public void showPref(){
  31. SharedPreferences pref = getApplicationContext()
  32. .getSharedPreferences("settings", MODE_PRIVATE);
  33. this.displayname = pref.getString("display-name", "");
  34.  
  35. this.tvShowPreference.setText(this.displayname);
  36. }
  37.  
  38. 3. Android Manifest
  39. <application
  40. android:allowBackup="true"
  41. android:icon="@mipmap/ic_launcher"
  42. android:label="@string/app_name"
  43. android:roundIcon="@mipmap/ic_launcher_round"
  44. android:supportsRtl="true"
  45. android:theme="@style/AppTheme"
  46. android:name=".BaseApplication">
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement