User Settings - Android

落花浮王杯 提交于 2019-12-01 10:55:45

There's actually multiple ways to persist changes. The Android documentation covers all of them in more detail, but essentially these are the five ways. Easiest is SharedPreferences, probably.

Shared Preferences

Store private primitive data in key-value pairs.

Internal Storage

Store private data on the device memory.

External Storage

Store public data on the shared external storage.

SQLite Databases

Store structured data in a private database.

Network Connection

Store data on the web with your own network server.

Use SharedPreferences. You can put key value pairs and retrieve when needed .

You need to store these settings within the Database. On how to use this see Using Databases

Use SharedPreferences

Save your settings:

SharedPreferences prefs = getSharedPreferences("myprefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit(); 
editor.putString("email", "my_email@email.com"); 
editor.putString("name", "Albert"); 
editor.commit(); 

Retrieve them:

SharedPreferences prefs = getSharedPreferences("myprefs",Context.MODE_PRIVATE);   
String email = prefs.getString("email", "default@email.com"); 

Thing that you could do is to create a PreferenceActivity like :

public class Prefs  extends PreferenceActivity  {   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference);
    }

}

In res/xml folder add preference.xml with this content :

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory android:title="General" >
        <CheckBoxPreference
            android:key="notification"
            android:summaryOff="You will not receive any notification"
            android:summaryOn="Notifications are sent to your device"
            android:title="Get notification" />
    </PreferenceCategory>

</PreferenceScreen>

In your code you can do now :

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean sendNotification = prefs.getBoolean("notification", false);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!