zoukankan      html  css  js  c++  java
  • Android数据存储之SharedPreferences

    SharedPreferences是一种轻型的数据存储方式,基于XML文件存储key-value pairs键值对数据,通常用来存储一些简单的配置信息。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。每一个 SharedPreferences 文件都是由framework管理的并且可以是私有或者可共享的。 

    数据存储

    新建一个Android项目,在MainActivity的onCreate方法中,调用getSharedPreferences方法,需要注意的是,如果已经存在文件则不会新建,如果键值对不存在则会继续添加到里面,如果存在名字相同,值不同则会覆盖原有的值。

            Context context=MainActivity.this;
            SharedPreferences shared=context.getSharedPreferences("Test", MODE_PRIVATE);
            Editor editor=shared.edit();
            editor.putString("Name", "FlyElephant");
            editor.putInt("Age", 24);
            editor.putBoolean("IsMarried", false);
            editor.commit();
    

     存储完之后这个时候之后就发现,文件夹下多了一个Test.xml,全路径应该是data/data/com.example.preference/shared_prefs/Test.xml

    导出之后发现xml中内容为:

    <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
    <map>
    <string name="Name">FlyElephant</string>
    <int name="Age" value="24" />
    <boolean name="IsMarried" value="false" />
    </map>
    

    显示数据

    设置一个按钮点击事件loadData

       public void loadData(View view){
        	SharedPreferences shared=MainActivity.this.getSharedPreferences("Test", MODE_PRIVATE);
            EditText editText=(EditText) findViewById(R.id.edit_sharedName);
            editText.setText(shared.getString("Name", ""));
            EditText editAge=(EditText) findViewById(R.id.edit_sharedAge);
            String ageString=String.valueOf(shared.getInt("Age", 0));
            editAge.setText(ageString);
        }

     数据显示结果:

    删除节点

    点击第二个按钮,执行的事件:

       public void deleteNode(View view) {
        	SharedPreferences shared=MainActivity.this.getSharedPreferences("Test", MODE_PRIVATE);
        	Editor editor=shared.edit();
        	editor.remove("Age");
        	editor.commit();
        	Toast.makeText(MainActivity.this, "删除成功",Toast.LENGTH_SHORT).show();
    	}

    效果如下:

    删除文件

    根据路径,调用一下File就直接删除了这个文件:

        public void deleteFile(View view){
        	String pathString="/data/data/"+getPackageName()+"/shared_prefs";
        	File file=new File(pathString,"Test.xml");
        	Log.i("com.example.preference",pathString);
        	if (file.exists()) {
    			file.delete();
    		}
          	Toast.makeText(MainActivity.this, "文件删除成功",Toast.LENGTH_SHORT).show();
        }
  • 相关阅读:
    Codeforces 992C(数学)
    Codeforces 990C (思维)
    Codeforces 989C (构造)
    POJ 1511 Invitation Cards(链式前向星,dij,反向建边)
    Codeforces 1335E2 Three Blocks Palindrome (hard version)(暴力)
    POJ 3273 Monthly Expense(二分)
    POJ 2566 Bound Found(尺取前缀和)
    POJ 1321 棋盘问题(dfs)
    HDU 1506 Largest Rectangle in a Histogram(单调栈)
    POJ 2823 Sliding Window(单调队列)
  • 原文地址:https://www.cnblogs.com/xiaofeixiang/p/4044683.html
Copyright © 2011-2022 走看看