数据存储:Internal Storage与Shared Preferences

    Android提供五种持久化数据存储的方式:Shared Preferences、Internal Storage、External Storage、SQLite Databases和Network Connection。文章如题讲的是Internal Storage和Shared Preferences。

    Internal Storage:通过文件的形式将数据保存到手机内部存储空间中,并且这些文件是私有的,其他程序无法访问。当卸载掉程序之后,这些文件也会被相应移除。读写操作:

①写数据时,调用openFileOutput(String name, int mode)方法获得一个输出流,参数一是输出的文件名而输出文件的路径是系统自定的/data/data/.../files/;参数二是操作模式,主要有两种模式:Context.MODE_PRIVATE,覆盖原有的文件;Context.MODE_APPEND,内容追加到原来的文件上。

②读数据时,调用openFileInput(String name)方法获得一个输入流,由于路径由系统自定,所以参数就是要读取数据的文件名

具体操作就是Java的I/O操作,可以参见http://blog.csdn.net/leelit/article/details/40040803

实例一:通过Internal Storage以文件形式存取数据

①布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="输入存储到文件的数据" />

    <EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="save data" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="输入要获取数据的文件名" />

    <EditText
        android:id="@+id/edittext1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="get data" />

</LinearLayout>
②Activity

public class MainActivity extends ActionBarActivity {

	private EditText editText; // 输入文件内容
	private EditText editText1; // 输入文件名
	private Button button;
	private Button button1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		editText = (EditText) findViewById(R.id.edittext);
		editText1 = (EditText) findViewById(R.id.edittext1);
		button = (Button) findViewById(R.id.button);
		button1 = (Button) findViewById(R.id.button1);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String data = editText.getText().toString();
				if (data != null && !data.equals("")) {
					saveDataToFile(data);
					Toast.makeText(MainActivity.this,
							"succeeded in saving data", Toast.LENGTH_LONG)
							.show();
				}
			}
		});
		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String fileName = editText1.getText().toString();
				if (!TextUtils.isEmpty(fileName)) {
					String data = getDataFromFile(fileName);
					System.out.println(data);
				}
			}
		});
	}

	// 调用openFileOutput方法获得一个输出流,输出流的路径系统自定,文件名为第一个参数
	private void saveDataToFile(String data) {
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		try {
			// 直接指定保存的文件名为leelit,第二个参数为保存方式
			fos = openFileOutput("leelit", Context.MODE_PRIVATE);
			bw = new BufferedWriter(new OutputStreamWriter(fos));
			bw.write(data);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// 调用openFileInput方法获得一个输入流,由于路径由系统自定,所以只需指明文件名
	private String getDataFromFile(String fileName) {
		StringBuilder builder = new StringBuilder();
		FileInputStream fis = null;
		BufferedReader br = null;

		try {
			fis = openFileInput(fileName);
			br = new BufferedReader(new InputStreamReader(fis));
			String line = "";
			while ((line = br.readLine()) != null)
				builder.append(line);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("File Not Found");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return builder.toString();
	}
}

一开始输入leelit,点击get data按钮打印:File Not Found;

输入你好,点击sava data,再次点击get data,打印:你好。使用的操作模式不同,文件内容可以被覆盖也可以是追加内容。


    

    Shared Preferences:通过xml文件的键值对形式将数据保存到手机内部存储空间中,并且数据是可以跨应用读写的。当卸载掉程序之后,这些文件也会被相应移除。读写操作:

写数据时:①调用getSharedPreferences(String name, int mode)获得一个SharedPreferences对象,参数一是输出的文件名而输出文件的路径是系统自定的/data/data/.../shared_prefs/;参数二是操作模式,主要有两种模式:Context.MODE_PRIVATE,Context.MODE_MULTI_PROCESS,顾名思义即可。②调用SharedPreferences对象edit方法获得一个Editor对象,存储数据,执行。

读数据时:用SharedPreferences对象获取数据

实例二:通过Shared Preferences以键值对形式本应用存取数据

①布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="save data" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get data" />

</LinearLayout>
②Activity

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button button = (Button) findViewById(R.id.button);
		Button button1 = (Button) findViewById(R.id.button1);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SharedPreferences sp = getSharedPreferences("leelit",
						Context.MODE_PRIVATE); // 获得SharedPreferences对象
				SharedPreferences.Editor editor = sp.edit(); // 获得Editor对象
				editor.putString("name", "leelit"); // 存放数据
				editor.putString("sex", "male");
				editor.commit(); // 执行
				Toast.makeText(MainActivity.this, "succeeded in saving data",
						Toast.LENGTH_LONG).show();
			}
		});

		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SharedPreferences sp = getSharedPreferences("leelit",
						Context.MODE_PRIVATE); // 获得SharedPreferences对象
				String name = sp.getString("name", null); // 获取数据
				String sex = sp.getString("sex", null);
				Toast.makeText(MainActivity.this,
						"name:" + name + "\nsex:" + sex, Toast.LENGTH_LONG)
						.show();
			}
		});

	}
}
先点击get data,吐司:name:null  sex:null;

点击save data后点击save data,吐司:name:leelit  sex:male




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值