美文网首页
Android中存取简单的数据

Android中存取简单的数据

作者: 大道至简峰 | 来源:发表于2016-02-29 17:30 被阅读90次
    Android中的存储
        使用Java IO流保存和访问数据
        使用SharedPreference保存和访问数据
        使用XmlSerializer保存和访问数据
    

    Android的存储

    在安卓中,我们可以将数据存储在应用的专属路径下或者存储在外部存储空间中,这是数据的存储位置。而存储方式有如下几种可以选择:

    • 使用Java IO流存储成文本文件,保存非常简单的数据。一般不使用这种方法
    • 使用SharedPreference存储为XML文件,保存零散的简单数据,推荐使用这种方法
    • 使用SQLite数据库存储
    • 使用XmlSerializer生成XML文件,保存复杂的数据。

    内部存储空间

    • RAM内存:运行内存,相当于电脑的内存
    • 每一个应用都一个专属的内部存储空间,其路径是data/data/应用的包名

    外部存储空间
    即SD卡。

    一个例子

    功能描述:用户输入相应的信息,然后点击相应的按钮后,程序将获取用户输入的信息,将其保存到内部存储空间中或者外部存储空间中。当用户退出再次进入后,所有的内容都是空的,这使用户可以通过点击相应的恢复按钮从内部存储或者SD卡中恢复以前用户保存的数据。

    应用界面.png
    主布局文件
    main_activity.xml
    <?xml version="1.0" encoding="utf-8"?>
    <!-- 
        最外层使用ScrollView包裹,以免输入法将输入信息的EditText顶不见了
     -->
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="4dp" >
    
            <TableLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:stretchColumns="1" >
    
                <TableRow>
                    <TextView
                        android:gravity="end"
                        android:text="@string/name" />
    
                    <EditText
                        android:id="@+id/name"
                        android:inputType="text" />
                </TableRow>
    
                <TableRow>
    
                    <TextView
                        android:gravity="end"
                        android:text="@string/age" />
    
                    <EditText
                        android:id="@+id/age"
                        android:inputType="number" />
                </TableRow>
    
                <TableRow android:layout_gravity="center_vertical" >
    
                    <TextView
                        android:gravity="end|bottom"
                        android:text="@string/sex" />
    
                    <RadioGroup
                        android:id="@+id/sex"
                        android:orientation="vertical" >
    
                        <RadioButton
                            android:id="@+id/rb_man"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/man" />
    
                        <RadioButton
                            android:id="@+id/rb_woman"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/woman" />
                    </RadioGroup>
                </TableRow>
    
                <TableRow>
    
                    <TextView
                        android:gravity="end"
                        android:text="@string/height" />
    
                    <EditText
                        android:id="@+id/height"
                        android:inputType="number" />
                </TableRow>
    
                <TableRow>
    
                    <TextView android:text="@string/english_level" />
    
                    <EditText
                        android:id="@+id/englishLevel"
                        android:hint="@string/english_level_prompt"
                        android:inputType="text" />
                </TableRow>
    
                <TableRow>
    
                    <TextView
                        android:gravity="end"
                        android:text="@string/school" />
    
                    <EditText
                        android:id="@+id/school"
                        android:inputType="text" />
                </TableRow>
    
                <TextView
                    android:layout_height="8dp"
                    android:background="#aaa" />
    
                <TableRow>
    
                    <TextView
                        android:gravity="end"
                        android:text="@string/location_data" />
    
                    <!-- android:editable="false"设置该EditText不可编辑 -->
                    <EditText
                        android:id="@+id/et_location_data"
                        android:editable="false"
                        android:inputType="none" />
                </TableRow>
            </TableLayout>
    
            <Button
                android:id="@+id/bt_save_using_javaIO"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="save"
                android:text="@string/save_using_javaIO" />
    
            <Button
                android:id="@+id/bt_save_using_sharedPreference"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="save"
                android:text="@string/save_using_sharedPrefrence" />
    
            <Button
                android:id="@+id/bt_save_using_XmlSerializer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="save"
                android:text="@string/save_using_xmlserializer" />
    
            <Button
                android:id="@+id/retrieve_usingJavaIO"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="retrieve"
                android:text="@string/retrieving_usingJavaIO" />
    
            <Button
                android:id="@+id/retrieve_usingSharedPreference"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="retrieve"
                android:text="@string/retrieve_usingSharedpreference" />
    
            <Button
                android:id="@+id/retrieve_usingXmlPullParser"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="retrieve"
                android:text="@string/retrieve_usingPullParser" />
        </LinearLayout>
    
    </ScrollView>
    

    字符
    strings.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <string name="app_name">Storage</string>
        <string name="hello_world">Hello world!</string>
        <string name="action_settings">Settings</string>
        <string name="name">姓名:</string>
        <string name="sex">性别:</string>
        <string name="height">身高:</string>
        <string name="school">毕业学校:</string>
        <string name="save_using_javaIO">使用JavaIO流保存数据</string>
        <string name="save_using_sharedPrefrence">使用SharedPreference保存数据</string>
        <string name="save_using_xmlserializer">使用XmlSerializer保存数据</string>
        <string name="retrieving_usingJavaIO">JavaIO数据回显</string>
        <string name="retrieve_usingSharedpreference">使用SharedPreference回显</string>
        <string name="retrieve_usingPullParser">使用Pull解析回显</string>
        <string name="location_data">数据位置:</string>
        <string name="age">年龄:</string>
        <string name="english_level">四六级:</string>
        <string name="english_level_prompt">填四级、六级或无</string>
        <string name="man">男</string>
        <string name="woman">女</string>
    
    </resources>
    
    

    清单文件
    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.ddzj.storage"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="14"
            android:targetSdkVersion="22" />
        <!--向SD卡中写入数据需要添加这条权限-->
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/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>
    
    

    入口Activity
    MainActivity.java

    package com.ddzj.storage;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    import org.xmlpull.v1.XmlPullParser;
    import org.xmlpull.v1.XmlPullParserException;
    import org.xmlpull.v1.XmlSerializer;
    
    import com.ddzj.storage.bean.Student;
    
    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.os.Bundle;
    import android.os.Environment;
    import android.util.Xml;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
        private EditText mName; // 名字
        private EditText mAge; // 年龄
        private RadioGroup mSex; // 性别
        private EditText mHeight; // 身高
        private EditText mEnglishLeve; // 英语等级
        private EditText mSchool; // 毕业学校
        private Student mStudent; // 用来保存学生信息的结构类
        private RadioButton mMan; // 男生单选按钮
        private RadioButton mWoman; // 女生单选按钮
        private EditText mDataLocation; // 用来显示数据保存的路径
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mName = (EditText) findViewById(R.id.name);
            mAge = (EditText) findViewById(R.id.age);
            mSex = (RadioGroup) findViewById(R.id.sex);
            mHeight = (EditText) findViewById(R.id.height);
            mEnglishLeve = (EditText) findViewById(R.id.englishLevel);
            mSchool = (EditText) findViewById(R.id.school);
            mMan = (RadioButton) findViewById(R.id.rb_man);
            mWoman = (RadioButton) findViewById(R.id.rb_woman);
            mDataLocation = (EditText) findViewById(R.id.et_location_data);
    
            mStudent = new Student();
        }
    
        /**
         * 当所有的具有android:onClick="save"属性的按钮被点击时都会调用这个方法
         * 我们在该方法中使用ID来判断哪一个按钮被点击
         */
        public void save(View v) {
            int id = v.getId();
    
            switch (id) {
            case R.id.bt_save_using_javaIO: 
                saveUsingJavaIO();// 使用JavaIO保存用户数据
                break;
            case R.id.bt_save_using_sharedPreference: 
                saveUsingSharedPreference(); // 使用SharedPreference保存用户数据
                break;
            case R.id.bt_save_using_XmlSerializer: 
                saveUsingXmlSerializer();// 将用户的数据以xml文件写入SD卡中
                break;
            }
        }
    
        /**
         * 使用XmlSerializer保存用户输入的数据
         */
        private void saveUsingXmlSerializer() {
    
            // 先得到用户输入的信息,如果输入的信息不完整,则提示。否则则保存信息
            if (!getStudentsInfo())
                return;
    
            // 使用Environment.getExternalStorageDirectory()来得到SD卡的路径,这里的文件保存在SD卡的根目录下
            File file = new File(Environment.getExternalStorageDirectory(), "stu.xml");
    
            // 得到一个Xml序列化对象
            XmlSerializer serializer = Xml.newSerializer();
    
            try {
                // 设置输出流
                serializer.setOutput(new FileOutputStream(file), "utf-8");
    
                // 开始写入用户的信息
                serializer.startDocument("utf-8", true);
    
                // 根节点
                serializer.startTag(null, "students");
    
                serializer.startTag(null, "student");
    
                // 写姓名节点
                serializer.startTag(null, "name");
                serializer.text(mStudent.getName());
                serializer.endTag(null, "name");
    
                // 写年龄节点
                serializer.startTag(null, "age");
                serializer.text(String.valueOf(mStudent.getAge()));
                serializer.endTag(null, "age");
    
                // 性别
                serializer.startTag(null, "sex");
                serializer.text(mMan.isChecked() ? "男" : "女");
                serializer.endTag(null, "sex");
    
                // 身高
                serializer.startTag(null, "height");
                serializer.text(String.valueOf(mStudent.getHeight()));
                serializer.endTag(null, "height");
    
                // 英语等级
                serializer.startTag(null, "englishLevel");
                serializer.text(mStudent.getEnglishLeve());
                serializer.endTag(null, "englishLevel");
    
                // 毕业学校
                serializer.startTag(null, "school");
                serializer.text(mStudent.getSchool());
                serializer.endTag(null, "school");
    
                serializer.endTag(null, "student");
                serializer.endTag(null, "students");
                serializer.endDocument();
    
                Toast.makeText(this, "保存成功:" + file.toString(), Toast.LENGTH_SHORT).show();
    
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    
        /**
         * 使用SharedPreference保存用户输入的数据
         */
        private void saveUsingSharedPreference() {
    
            // 先得到用户输入的信息,如果输入的信息不完整,则提示。否则则保存信息
            if (!getStudentsInfo())
                return;
            /*
             * 使用上下文的getSharedPreferences("文件名",文件模式)的方法可以得到一个SharedPreference对象
             * 
             * 使用SharedPreference保存文件的路径是:data/data/包名/shared_prefs/文件名.xml
             * 
             * 通过SharedPreference对象得到一个Editor对象,通过Editor对象写入数据,然后提交。
             */
            SharedPreferences preferences = getSharedPreferences("stu", MODE_PRIVATE);
            Editor editor = preferences.edit(); // 得到一个编辑器
            // 写入数据
            editor.putString("name", mStudent.getName());
            editor.putInt("age", mStudent.getAge());
            editor.putString("sex", mStudent.getSex());
            editor.putFloat("height", (float) mStudent.getHeight());
            editor.putString("englishLevel", mStudent.getEnglishLeve());
            editor.putString("school", mStudent.getSchool());
            // 提交
            editor.commit();
    
            Toast.makeText(this, "使用SharedPreference保存成功!", Toast.LENGTH_SHORT).show();
    
            mDataLocation.setText("data/data/com.ddzj.storage/shared_prefs/stu.xml");
        }
    
        /**
         * 使用JavaIO流将用户输入的数据保存到应用的内部存储空间中
         */
        private void saveUsingJavaIO() {
    
            // 先得到用户输入的信息,如果输入的信息不完整,则提示。否则则保存信息
            if (!getStudentsInfo())
                return;
    
            /*
             * 保存到内部存储空间,每一个应用都有自己的独立存储空间,路径为:data/data/包名
             * 
             * 获取File对象的方法: 1. File f = new File("data/data/包名/文件名"); 2. File f2 =
             * new File(getFilesDir(),"文件名"); 3. File f3 = new
             * File(getChacheDir(),"文件名"); 4. File f4 = new
             * File(Environment.getExternalStorageDirectory(),"文件名");
             */
            File f = new File("data/data/com.ddzj.storage/stu.txt");
            // File f2 = new File(getFilesDir(),"stu2.txt");
            // File f3 = new File(getCacheDir(),"stu3.txt");
            // File f4 = new File(Environment.getExternalStorageDirectory(),"stu4.txt");
    
            StringBuilder sb = new StringBuilder();
            sb.append(mStudent.getName());
            sb.append("\n");
            sb.append(mStudent.getAge());
            sb.append("\n");
            sb.append(mStudent.getSex());
            sb.append("\n");
            sb.append(mStudent.getHeight());
            sb.append("\n");
            sb.append(mStudent.getEnglishLeve());
            sb.append("\n");
            sb.append(mStudent.getSchool());
            sb.append("\n");
    
            BufferedWriter bw = null;
            try {
                bw = new BufferedWriter(new FileWriter(f));
                bw.write(sb.toString());
                Toast.makeText(this, "使用JavaIO保存成功", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (bw != null) {
                    try {
                        bw.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
    
            mDataLocation.setText(f.toString());
        }
    
        /**
         * 得到用户输入的信息
         * 
         * @return 如果用户输入的信息正确,返回true,否则返回false
         */
        private boolean getStudentsInfo() {
            String name = mName.getText().toString();
            if ("".equals(name)) {
                Toast.makeText(this, "名字不能为空", Toast.LENGTH_SHORT).show();
                return false;
            }
            String age = mAge.getText().toString();
            if ("".equals(age)) {
                Toast.makeText(this, "年龄不能为空", Toast.LENGTH_SHORT).show();
                return false;
            }
            String sex = mSex.getCheckedRadioButtonId() == R.id.rb_man ? "男" : "女";
            if ("".equals(sex)) {
                Toast.makeText(this, "性别不能为空", Toast.LENGTH_SHORT).show();
                return false;
            }
            String height = mHeight.getText().toString();
            if ("".equals(height)) {
                Toast.makeText(this, "身高不能为空", Toast.LENGTH_SHORT).show();
                return false;
            }
            String englishLevel = mEnglishLeve.getText().toString();
            if ("".equals(englishLevel)) {
                Toast.makeText(this, "英语等级不能为空", Toast.LENGTH_SHORT).show();
                return false;
            }
            String school = mSchool.getText().toString();
            if ("".equals(school)) {
                Toast.makeText(this, "毕业学校不能为空", Toast.LENGTH_SHORT).show();
                return false;
            }
    
            mStudent.setInfo(name, Integer.parseInt(age), sex, Double.parseDouble(height), englishLevel, school);
    
            return true;
        }
    
        /**
         * 恢复用户的信息
         * 
         * @param v
         *            被点击的按钮
         */
        public void retrieve(View v) {
            int id = v.getId();
            switch (id) {
            case R.id.retrieve_usingJavaIO: // 使用JavaIO流恢复
                retrieveUsingJavaIO();
                break;
            case R.id.retrieve_usingSharedPreference: // 使用SharedPreference恢复
                retrieveUsingSharedPreference();
                break;
            case R.id.retrieve_usingXmlPullParser: // 解析Xml文件恢复
                retrieveUsingXmlPullParser();
                break;
            }
        }
    
        /**
         * 将保存在SD卡根目录的用户信息恢复到相应的控件中
         */
        private void retrieveUsingXmlPullParser() {
    
            // Get the file storing user informations.
            File file = new File(Environment.getExternalStorageDirectory(), "stu.xml");
    
            if (!file.exists()) {
                Toast.makeText(this, "Nothing to retrieve!", Toast.LENGTH_SHORT).show();
                return;
            }
    
            String name = "";
            int age = 0;
            String sex = "";
            double height = 0;
            String englishLevel = "";
            String school = "";
    
            XmlPullParser xmlParse = Xml.newPullParser();
            try {
                xmlParse.setInput(new FileInputStream(file), "utf-8");
    
                int type = xmlParse.getEventType();
    
                while (type != XmlPullParser.END_DOCUMENT) {
    
                    switch (type) {
                    case XmlPullParser.START_TAG:
                        if ("name".equals(xmlParse.getName())) {
                            name = xmlParse.nextText();
                        } else if ("age".equals(xmlParse.getName())) {
                            age = Integer.parseInt(xmlParse.nextText());
                        } else if ("sex".equals(xmlParse.getName())) {
                            sex = xmlParse.nextText();
                        } else if ("height".equals(xmlParse.getName())) {
                            height = Double.parseDouble(xmlParse.nextText());
                        } else if ("englishLevel".equals(xmlParse.getName())) {
                            englishLevel = xmlParse.nextText();
                        } else if ("school".equals(xmlParse.getName())) {
                            school = xmlParse.nextText();
                        }
                        break;
                    }
                    type = xmlParse.next();
                }
                retrieveStudentInfo(name, age, sex, height, englishLevel, school);
    
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            mDataLocation.setText(file.toString());
        }
    
        /**
         * 将保存在data/data/com.ddzj.storage/shared_prefs中的stu.xlm文件中的信息恢复到相应的控件中
         */
        private void retrieveUsingSharedPreference() {
    
            SharedPreferences preferences = getSharedPreferences("stu", MODE_PRIVATE);
    
            String name = preferences.getString("name", "");
            int age = preferences.getInt("age", 0);
            String sex = preferences.getString("sex", "");
            float height = preferences.getFloat("height", 0);
            String englishLevel = preferences.getString("englishLevel", "");
            String school = preferences.getString("school", "");
    
            retrieveStudentInfo(name, age, sex, height, englishLevel, school);
            
            mDataLocation.setText("data/data/com.ddzj.storage/shared_prefs/stu.xml");
        }
    
        /**
         * 使用JavaIO恢复写入的文件
         */
        private void retrieveUsingJavaIO() {
            File file = new File("data/data/com.ddzj.storage/stu.txt");
    
            BufferedReader br = null;
    
            try {
                br = new BufferedReader(new FileReader(file));
                String name = br.readLine();
                int age = Integer.parseInt(br.readLine());
                String sex = br.readLine();
                double height = Double.parseDouble(br.readLine());
                String englishLevel = br.readLine();
                String school = br.readLine();
    
                retrieveStudentInfo(name, age, sex, height, englishLevel, school);
                
                mDataLocation.setText(file.toString());
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        /**
         * 将内存中的学生信息恢复到相应的控件中
         * 
         * @param name
         *            名字
         * @param age
         *            年龄
         * @param sex
         *            性别
         * @param height
         *            身高
         * @param englishLevel
         *            英语等级
         * @param school
         *            毕业学校
         */
        private void retrieveStudentInfo(String name, int age, String sex, double height, String englishLevel,
                String school) {
            if ("".equals(name)) {
                Toast.makeText(this, "没有数据可以恢复!", Toast.LENGTH_SHORT).show();
                return;
            }
            mName.setText(name);
            mAge.setText(String.valueOf(age));
            if ("男".equals(sex)) {
                mMan.setChecked(true);
            } else {
                mWoman.setChecked(true);
            }
            mHeight.setText(String.valueOf(height));
            mEnglishLeve.setText(englishLevel);
            mSchool.setText(school);
            Toast.makeText(this, "恢复成功!", Toast.LENGTH_SHORT).show();
        }
    }
    

    用来保存数据的结构类
    Student.java

    package com.ddzj.storage.bean;
    
    public class Student {
        private String name;
        private int age;
        private String sex;
        private double height;
        private String school;
        private String englishLeve;
        
        public Student(){}
        public Student(String name, int age, String sex, double height, String school, String englishLeve) {
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.height = height;
            this.school = school;
            this.englishLeve = englishLeve;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public double getHeight() {
            return height;
        }
        public void setHeight(double height) {
            this.height = height;
        }
        public String getSchool() {
            return school;
        }
        public void setSchool(String school) {
            this.school = school;
        }
        public String getEnglishLeve() {
            return englishLeve;
        }
        public void setEnglishLeve(String englishLeve) {
            this.englishLeve = englishLeve;
        }
        public void setInfo(String name, int age, String sex, double height, String englishLeve, String school) {
            // TODO Auto-generated method stub
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.height = height;
            this.school = school;
            this.englishLeve = englishLeve;
        }
    }
    

    相关文章

      网友评论

          本文标题:Android中存取简单的数据

          本文链接:https://www.haomeiwen.com/subject/jtygkttx.html