Android数据持久化存储(一)

本文介绍了Android中数据持久化的一种方式——SharedPreferences,详细讲解了如何使用SharedPreferences对象来保存和读取用户偏好,包括其XML和Java实现,并讨论了不同存储模式的权限和用法。同时提到了内部存储和外部存储SD卡的使用方法。
摘要由CSDN通过智能技术生成

1SharedPreferces 是一种轻量级的数据存储机制,用来存一些简单的数据。适合key–value类的数据;

1保存和读取用户偏好使用到SharedPreferences对象保存数据。

用户的偏好:比如用户的字体设置,颜色设置等等;

在这里插入图片描述
.xml

	<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:weightSum="1">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <EditText
        android:id="@+id/edit1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:hint="请输入需要的内容"/>
    <Button
        android:layout_weight="1"
        android:id="@+id/btn_Save"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="存入到sharepreference"
        android:layout_marginLeft="5dp"
        android:textSize="10dp"
        android:onClick="Click"/>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <EditText
        android:id="@+id/edit2"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:hint="请输入需要的内容"/>
    <Button
        android:layout_weight="1"
        android:id="@+id/btn_Get"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="从sharepreference取出"
        android:layout_marginLeft="5dp"
        android:onClick="Click"
        android:textSize="10dp"/>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <EditText
        android:id="@+id/edit3"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:hint="请输入需要的内容"/>
    <Button
        android:layout_weight="1"
        android:id="@+id/btn_Set"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="从sharepreference设置"
        android:layout_marginLeft="5dp"
        android:onClick="Click"
        android:textSize="10dp"/>

</LinearLayout>

.java

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends AppCompatActivity {

private EditText meditText1 ,meditText2, meditText3;
private Button SaveBtn,GetBtn;
//声明Sharedpreferenced对象
private SharedPreferences sp ;


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

    meditText1= (EditText) findViewById(R.id.edit1);
    meditText2 = (EditText) findViewById(R.id.edit2);
    meditText3 = (EditText) findViewById(R.id.edit3);
    SaveBtn = (Button) findViewById(R.id.btn_Save);
    GetBtn = (Button) findViewById(R.id.btn_Get);
}

public void Click(View view) {
    /**
     * 获取SharedPreferenced对象
     * 第一个参数是生成xml的文件名
     * 第二个参数是存储的格式(**注意**本文后面会讲解)
     */
    sp = getSharedPreferences("User", Context.MODE_PRIVATE);
    switch (view.getId()){
        case R.id.btn_Save:
            //获取到edit对象
            SharedPreferences.Editor edit = sp.edit();
            //通过editor对象写入数据
            //这里的Value和后一个参数相当于key--value;
            edit.putString("Value",meditText1.getText().toString().trim());
            //提交数据存入到xml文件中
            edit.commit();
            break;
        case R.id.btn_Get:
            //取出数据,第一个参数是写入是的键,第二个参数是如果没有获取到数据就默认返回的值。
            String value = sp.getString("Value","Null");
            meditText2.setText(value);
            break;
        case R.id.btn_Set:
            //取出数据,第一个参数是写入是的键,第二个参数是如果没有获取到数据就默认返回的值。
            SharedPreferences.Editor edit2 = sp.edit();
            //通过editor对象写入数据
            edit2.putString("Value",meditText3.getText().toString().trim());
            //提交数据存入到xml文件中
            edit2.commit();
            break;
    }
    }
    }

==注意;==需要注意:getSharedPreferences(“User”, Context.MODE_PRIVATE)方法中第二个参数需要了解Android的四种枚举方式下面是详细的解释:
私有模式
Context.MODE_PRIVATE 的值是 0;
①只能被创建这个文件的当前应用访问
②若文件不存在会创建文件;若创建的文件已存在则会覆盖掉原来的文件

追加模式
Context.MODE_APPEND 的值是 32768;
①只能被创建这个文件的当前应用访问
②若文件不存在会创建文件;若文件存在则在文件的末尾进行追加内容

可读模式
Context.MODE_WORLD_READABLE的值是1;
①创建出来的文件可以被其他应用所读取

可写模式
Context.MODE_WORLD_WRITEABLE的值是2
①允许其他应用对其进行写入。

保存到内部存储;

在这里插入图片描述
这里面包含了文件简单的的输入输出
,xml

		    <TextView
		        android:text="数据保存"
		        android:id="@+id/text1"
		        android:layout_width="fill_parent"
		        android:layout_height="65dp" />
		
		    <EditText
		        android:id="@+id/text2"
		        android:layout_width="fill_parent"
		        android:layout_height="79dp" />
		
		    <Button
		        android:id="@+id/but1"
		        android:text="save"
		        android:onClick="onClickSave"
		        android:layout_width="match_parent"
		        android:layout_height="wrap_content" />
		
		    <Button
		        android:id="@+id/but2"
		        android:text="load"
		        android:onClick="onClickLoad"
		        android:layout_width="match_parent"
		        android:layout_height="wrap_content" />
		 
		</LinearLayout>

.java

		import android.content.Context;
		import android.content.Intent;
		import android.content.SharedPreferences;
		import android.os.Bundle;
		import android.support.v7.app.AppCompatActivity;
		import android.view.Menu;
		import android.view.MenuItem;
		import android.view.View;
		import android.widget.Button;
		import android.widget.EditText;
		import android.widget.TextView;
		import android.widget.Toast;
		
		import org.apache.http.util.EncodingUtils;
		
		import java.io.FileInputStream;
		import java.io.FileNotFoundException;
		import java.io.FileOutputStream;
		import java.io.IOException;
		import java.io.InputStreamReader;
		import java.io.OutputStreamWriter;
		
		
		public class MainActivity extends AppCompatActivity {
		    EditText text2;
		    TextView text1;
		    static final int READ_BLOCK_SIZE = 100;
		
		
		
		    protected void onCreate(Bundle savedInstanceState) {
		        super.onCreate(savedInstanceState);
		        setContentView(R.layout.activity_main);
		        text2 = (EditText)findViewById(R.id.text2);
		        text1 = (TextView)findViewById(R.id.text1);
		    }
		
		//将数据保存到文件中;
		    public void onClickSave(View view)
		    {
		        String str = text2.getText().toString();
		        try{
		            FileOutputStream fOut = openFileOutput("textfile.txt",MODE_PRIVATE);
		            OutputStreamWriter osw = new OutputStreamWriter(fOut);
		            osw.write(str);
		            osw.flush();
		            osw.close();
		            Toast.makeText(getBaseContext(),"File saved successfully", Toast.LENGTH_LONG).show();
		            text2.setText("");
		        } catch (FileNotFoundException e) {
		            e.printStackTrace();
		        } catch (IOException e) {
		            e.printStackTrace();
		        }
		    }
		//从文件中读取文件;
		    public void onClickLoad(View view) {//
		        try {
		            FileInputStream fis;
		            fis = openFileInput("textfile.txt");
		            byte[] buffer = new byte[1024];
		            fis.read(buffer);
		            String fileContent = EncodingUtils.getString(buffer, "UTF-8");
		            text2.setText("");
		            text1.setText(fileContent);
		            Toast.makeText(getBaseContext(), "File loaded successfully", Toast.LENGTH_SHORT).show();
		        } catch (FileNotFoundException e) {
		            e.printStackTrace();
		        } catch (IOException e) {
		            e.printStackTrace();
		        }
		    }
		}

保存到外部存储SD卡中。

第一步在manifest.xml中提供权限
.xml

	<?xml version="1.0" encoding="utf-8"?>
	<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	    package="com.example.dell.menmorize" >
	    <!--提供权限-->
	    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
	    <application
	        android:allowBackup="true"
	        android:icon="@mipmap/ic_launcher"
	        android:label="@string/app_name"
	        android:theme="@style/AppTheme" >
	        <activity
	            android:name=".MainActivity"
	            android:label="@string/app_name" >
	            <intent-filter>
	                <action android:name="android.intent.action.MAIN" />
	
	                <category android:name="android.intent.category.LAUNCHER" />
	            </intent-filter>
	        </activity>
	    </application>
	
	</manifest>

main.xml

	<LinearLayout
	    xmlns:android="http://schemas.android.com/apk/res/android"
	    xmlns:tools="http://schemas.android.com/tools"
	    android:orientation="vertical"
	    android:layout_width="match_parent"
	    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
	    android:paddingRight="@dimen/activity_horizontal_margin"
	    android:paddingTop="@dimen/activity_vertical_margin"
	    android:paddingBottom="@dimen/activity_vertical_margin"
	    tools:context=".MainActivity"
	    android:weightSum="1">
	
	    <TextView
	    android:text="数据保存"
	    android:id="@+id/text1"
	    android:layout_width="fill_parent"
	    android:layout_height="65dp" />
	
	    <EditText
	    android:id="@+id/text2"
	    android:layout_width="fill_parent"
	    android:layout_height="79dp" />
	
	    <Button
	    android:id="@+id/but1"
	    android:text="save"
	    android:onClick="onClickSave"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content" />
	
	    <Button
	    android:id="@+id/but2"
	    android:text="load"
	    android:onClick="onClickLoad"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content" />
	</LinearLayout>

.java

	import android.content.Context;
	import android.content.Intent;
	import android.content.SharedPreferences;
	import android.os.Bundle;
	import android.os.Environment;
	import android.support.v7.app.AppCompatActivity;
	import android.view.Menu;
	import android.view.MenuItem;
	import android.view.View;
	import android.widget.Button;
	import android.widget.EditText;
	import android.widget.TextView;
	import android.widget.Toast;
	
	import org.apache.http.util.EncodingUtils;
	
	import java.io.File;
	import java.io.FileInputStream;
	import java.io.FileNotFoundException;
	import java.io.FileOutputStream;
	import java.io.IOException;
	import java.io.InputStreamReader;
	import java.io.OutputStreamWriter;
	
	
	public class MainActivity extends AppCompatActivity {
	        EditText text2;
	    TextView text1;
	    static final int READ_BLOCK_SIZE = 100;
	
	
	//    这是第一个例子
	    private EditText meditText1, meditText2, meditText3;
	    private Button SaveBtn, GetBtn;
	    //声明Sharedpreferenced对象
	    private SharedPreferences sp;
	//     以上是第一个例子
	
	//    这是第二个例子
	//    EditText text2;
	//    TextView text1;
	//    static final int READ_BLOCK_SIZE = 100;
	//    以上第二个例子
	        protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_main);
	        text2 = (EditText)findViewById(R.id.text2);
	        text1 = (TextView)findViewById(R.id.text1);
	    }
	
	    public void onClickSave(View view)
	    {
	        File sdcard = Environment.getExternalStorageDirectory();
	        String str = text2.getText().toString();
	        try{
	        //得到路径
	            File directory = new File(sdcard.getAbsolutePath()+".myfiles");
	            //创建文件夹
	            directory.mkdir();
	            File file = new File (directory, "textfile.txt");
	            FileOutputStream fOut = new FileOutputStream(file);
	            OutputStreamWriter osw = new OutputStreamWriter(fOut);
	            osw.write(str);
	            osw.flush();
	            osw.close();
	            //输出提示信息
	            Toast.makeText(getBaseContext(),"File saved successfully", Toast.LENGTH_LONG).show();
	            text2.setText("");
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	
	    public void onClickLoad(View view) {
	        try {
	            File sdcard = Environment.getExternalStorageDirectory();
	            File directory = new File(sdcard.getAbsolutePath()+"/myfiles");
	            File file = new File(directory, "textfile.txt");
	
	            FileInputStream fis = new FileInputStream(file);
	            byte[] buffer = new byte[1024];
	            fis.read(buffer);
	            //这个非常重要,不然提取出来输出的是乱码;
	            String fileContent = EncodingUtils.getString(buffer, "UTF-8");
	            text2.setText("");
	            text1.setText(fileContent);
	            Toast.makeText(getBaseContext(), "File loaded successfully", Toast.LENGTH_SHORT).show();
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	}

在二中我将介绍数据库的用法点着进入数据库二
Android数据持久化存储(二)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值