• android学习笔记45——android的数据存储和IO


    android的数据存储和IO

    SharedPreferences与Editor简介

    SharedPreferences保存的数据主要是类似于配置信息格式的数据,因此其保存的数据主要是简单的类型的key-value对。

    SharedPreferences接口主要负责读取应用程序的Preperences数据,其提供了如下常用方法访问SharedPreferences中的key-value:

    boolean contains(String key) 判断SharedPreferences是否包含指定的key的数据
    abstract Map(String,?) getAll() 获取SharedPreferences里面所有的key-value对
    boolean getXxx(String key,xxx defValue)

    获取SharedPreferences数据里指定的key对应的value.如果key不存在,则默认返回

    defValue,其中xxx可以是boolean、float、int、long、String等各种基本类型的值.

    SharedPreferences本身没有提供写入数据的能力,而是通过SharedPreferences的内部接口,SharedPreferences调用edit()方法即可获取其对应的Editor对象。

    Editor对象提供了如下方法想SharedPreferences写入数据:

    SharedPreferences.Editor clear() 清空SharedPreferences里所有数据
    SharedPreferences.Editor putXxx(String key,xxx value) 向SharedPreferences存入指定的key对应的数据.其中xxx可以是boolean、float、int、long、String等各种基本类型的值.
    SharedPreference.Editor remove(String key) 删除SharedPreference里面指定的key对应的数据 
    boolean commit() 当Editor完成后,调用commit()提交修改 

    SharedPreference本身是一个接口,无法创建实例,只能通过Context提供getSharedPreferences(String name,int mode)方法来获取SharedPreference实例,该方法

    的第二个参数支持如下几个值:

    Context.MODE_PRIVATE 指定该SharedPreference数据只能被本地应用程序读、写
    Context.MODE_WORLD_READABLE 指定该SharedPreference数据能被其他应用程序读、但不能写
    Context.MODE_WORLD_WRITEABLE 指定该SharedPreference数据能被其他应用程序读、写

    实例一:

    布局文件==》
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        tools:context=".MainActivity" >
    
        <Button
            android:id="@+id/btnRead"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="read" />
    
        <Button
            android:id="@+id/btnWrite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="write" />
    
    </LinearLayout>
    
    代码实现==>
    package com.example.mysharedpreferences;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;
    
    public class MainActivity extends Activity
    {
    	SharedPreferences preferences;
    	SharedPreferences.Editor editor;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState)
    	{
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		// 获取只能被本地应用程序读写的SharedPreferences 对象
    		preferences = getSharedPreferences("crazyit", MODE_PRIVATE);
    		editor = preferences.edit();
    
    		Button btnRead = (Button) this.findViewById(R.id.btnRead);
    		Button btnWrite = (Button) this.findViewById(R.id.btnWrite);
    		btnRead.setOnClickListener(new MyButtonClick());
    		btnWrite.setOnClickListener(new MyButtonClick());
    	}
    
    	private class MyButtonClick implements OnClickListener
    	{
    		@Override
    		public void onClick(View v)
    		{
    			switch (v.getId())
    			{
    			case R.id.btnRead:
    				// 读取字符串数据
    				String time = preferences.getString("time", null);
    				// 读取int数据
    				int num = preferences.getInt("num", 0);
    				String result = time == null ? "您暂时还未写入数据" : "写入时间为:" + time + "
    上次随机产生的数字为" + num;
    				Toast.makeText(MainActivity.this, result, 5000).show();
    				break;
    			case R.id.btnWrite:
    				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
    				// 存入当前时
    				editor.putString("time", sdf.format(new Date()));
    				editor.putInt("num", (int) (Math.random() * 100));
    				// 提交所有存入的数据
    				editor.commit();
    				break;
    			}
    		}
    
    	}
    
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu)
    	{
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.main, menu);
    		return true;
    	}
    
    }
    

    运行效果:

    实例二:

    读写其他应用程序SharedPreferences

     注意:要读写其他应用程序的SharedPreferences,前提是创建该SharedPreferences的应用程序指定相应的访问权限。

    实现读取其他应用程序的SharedPreferences的操作步骤:

    1.创建其他程序对应的Context,Eg:useCount = createPackageContext("org.crazyit.io",Context.CONTEXT_IGNORE_SECURITY);  ----"org.crazyit.io"包名称

    2.调用其他应用程序的Context的getSharedPreferences(String key,int mode)即可获取相应的SharedPreferences对象

    3.如果需要向其他应用的SharedPreferences数据写入数据,调用SharedPreferences的edit()方法获取相应的Editor即可。

    如下程序实现如何读取上一个实例中所保存的SharedPreferences数据:

    注意:开发者也可通过IO的方式读取SharedPreferences对应的XMl文件,再通过解析来获取数据也是可行的。IO方式比较繁琐,不建议使用...

  • 相关阅读:
    将博客搬至CSDN
    第一章 spring起步
    动态规划-最长非降子序列
    硬币问题-动态规划详解
    哲学家就餐
    java并发编程(十九)障碍器CyclicBarrier
    java并发编程(十八)阻塞队列和阻塞栈
    java并发编程(十七)Executor框架和线程池
    java并发编程(十七)内存操作总结
    java并发编程(十六)happen-before规则
  • 原文地址:https://www.cnblogs.com/YYkun/p/5951998.html
Copyright © 2020-2023  润新知