Android Sample Code之API Demos (Activity三):Persistent State 《保存数据SharedPreferences》

本文档详细介绍了在Android中如何在Activity状态改变时保存和恢复数据,重点关注SharedPreferences的使用。SharedPreferences提供了一种简单的方法来存储软件参数,数据在退出应用后仍能保留,存储在XML文件中。通过两个主要步骤——保存和获取数据,可以轻松实现数据的持久化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇文档教你在activity状态改变时如何保存和恢复数据!

上代码PersistentState.java:

public class PersistentState extends Activity
{
    /**
     * Initialization of the Activity after it is first created.  Here we use
     * {@link android.app.Activity#setContentView setContentView()} to set up
     * the Activity's content, and retrieve the EditText widget whose state we
     * will persistent.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Be sure to call the super class.
        super.onCreate(savedInstanceState);

        // See assets/res/any/layout/save_restore_state.xml for this
        // view layout definition, which is being set here as
        // the content of our screen.
        setContentView(R.layout.save_restore_state);

        // Set message to be appropriate for this screen.
        ((TextView)findViewById(R.id.msg)).setText(R.string.persistent_msg);

        // Retrieve the EditText widget whose state we will save.
        mSaved = (EditText)findViewById(R.id.saved);
    }

    /**
     * Upon being resumed we can retrieve the current state.  This allows us
     * to update the state if it was changed at any time while paused.
     */
    @Override
    protected void onResume() {
        super.onResume();

        SharedPreferences prefs = getPreferences(0); 
        String restoredText = prefs.getString("text", null);
        if (restoredText != null) {
            mSaved.setText(restoredText, TextView.BufferType.EDITABLE);

            int selectionStart = prefs.getInt("selection-start", -1);
            int selectionEnd = prefs.getInt("selection-end", -1);
            if (selectionStart != -1 && selectionEnd != -1) {
                mSaved.setSelection(selectionStart, selectionEnd);
            }
        }
    }

    /**
     * Any time we are paused we need to save away the current state, so it
     * will be restored correctly when we are resumed.
     */
    @Override
    protected void onPause() {
        super.onPause();

        SharedPreferences.Editor editor = getPreferences(0).edit();
        editor.putString("text", mSaved.getText().toString());
        editor.putInt("selection-start", mSaved.getSelectionStart());
        editor.putInt("selection-end", mSaved.getSelectionEnd());
        editor.commit();
    }

    private EditText mSaved;
}
这里使用SharedPreferences类,在pause时存储数据,resume时恢复。

SharedPreferences类是个轻量级的存储类,比文件和数据库方便多了,最适合存储软件参数,当软件退出后,参数还被保留,其实这些数据是存在xml文件中的,在/data/data/<package name>/shared_prefs目录下。

使用起来很简单:

1、使用SharedPreferences保存数据

Editor sharedata = getSharedPreferences("data", 0).edit();  //获取编辑器,产生文件data.xml
sharedata.putString("item","hello getSharedPreferences");  //用编辑器写要保存的数据,第一个参数是id,后面是value
sharedata.commit();//最后提交,切记!!!


2、使用SharedPreferences获取数据

SharedPreferences sharedata = getSharedPreferences("data", 0);  //取得data.xml
String data = sharedata.getString("item", null); //取得所需数据




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值