ym——Android从零开始(6)(Sdcard文件操作+pull解析+ SharedPreferences)(新)

转载请注明本文出自CYM的博客(http://blog.csdn.net/cym492224103),谢谢支持!


前言

在开发中很多信息,我们都会存储在手机内部,比如一个设置,等等。此章节就是讲解如何将信息存储到文件,还会给大家带来实战工具类之一 PreferencesUtils


文件的操作(SD卡)

写一个文件在SD卡

1> 配置权限

<!-- 老版本,考虑兼容性 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- SD卡写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2> 得到外存储器(SD卡)的路径

File dir = Environment.getExternalStorageDirectory();
File file = new File(dir , name);

3> 创建一个输出流

FileOutputStream fos = new FileOutputStream(file);

4> 写入流

fos.write(content.getBytes());

5> 关闭流

fos.closed();


XmlPullParser解析

解析XML

1> 得到XmlPullParserFactory  解析器工厂

XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();

2>新的一个解析器XmlPullParser

XmlPullParser parser = parserFactory.newXmlPullParser();

3> 得到要解析的XML 文件流

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(“XX.xml”);

注意

this.getClass().getClassLoader().getResourceAsStream(“XX.xml”);获得src根目录下的文件
this.getClass().getResourceAsStream(“XX.xml”);获得当前操作对象的所在包下

4> 给解析器设置文件流和编码格式

parser.setInput(inputStream,”utf-8”);

5> 得到解析事件类型

INT EVENTTYPE = parser.getEventType();

6> 开始判断读取文件

>> 判断是否解析到结束标签

While(eventType != parser.END_DOCUMENT){
Swich(eventType){

>> 开始标签

Case:parser.STAR_TAG

>> 读取标签里面的内容

If(“persons”.equals(parser.getName)){
persons = new ArrayList<Person>();
}else if("person".equals(parser.getName())){
         person = new Person();
int id = Integer.parseInt(parser.getAttributeValue(0));
         person.id = id;
}else if("age".equals(parser.getName())){
int age = Integer.parseInt(parser.nextText());
person.age = age;
}
Berak;

>> 结束标签

Case:parser.END_TAG
If(“person”.equals(parser.getName)){
List.add(person);
Person=null;
}
Break;
Default:
Break;
}
//执行下一个标签
eventType.next();
}
inputStream.close();


生成一个XML文件

1> 得到解析工厂

XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();

2> 得到序列化器

XmlSerializer serializer = parserFactory.newSerializer();

3> 创建一个XML,并设置它的模式

FileOutputStream os = new FileOutput(“XX.xml”,Context.MODE_PRIVATE);

4> 给序列化器指定文件输入流和编码

serializer.setInput(os,”utf-8”);

5> 生成文档头指定编码格式和是否是一个独立的文件

serializer.starDocument(“utf-8”,ture);

6> 生成(根)根节点

serializer.starTag(null,tagName);

7> 迭代集合

for(Lisr<XX> li : list){
serializer.starTag(null,tagName);
Serializer.attribute(null,tagName,ls.value);
serializer.endTag(null,tagName);
}

8> 结束(根)根标签

Serializer.endTag(null,tagName);

9> 生成文档结尾

serializer.endDocument();

10> 关闭流

os.close();


SharedPreferences(共享首选项)

SharedPreferences 可以方便的存储参数,首选项就是用户设置的操作信息,xml的形式保存

比如游戏中的设置每次设置完后就回对你的设置进行


保存选项信息

1> 得到首选项

SharedPreference sp= getSharePreference(fileName,mode);

2> 得到编辑器

Editor editor = sp.edit();

3> 通过编辑器修改值

editor.setString(nameTag,value);

4> 提交提交信息

editor.commit();

读取信息

1> 得到首选项

SharedPreference sp = getSharedPreference(fileName,mode)

2> 根据首选项得到数据

String name = sp.getString(nameTag,””);

3> 绑定值

可存储数据类型:长 布尔整型浮点字符串



在实战项目中会把SharedPreference写成一个公共类,方便多人共同使用,因为很实用:

package com.chronocloud.lib.util;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * PreferencesUtils, easy to get or put data
 * <ul>
 * <strong>Preference Name</strong>
 * <li>you can change preference name by {@link #PREFERENCE_NAME}</li>
 * </ul>
 * <ul>
 * <strong>Put Value</strong>
 * <li>put string {@link #putString(Context, String, String)}</li>
 * <li>put int {@link #putInt(Context, String, int)}</li>
 * <li>put long {@link #putLong(Context, String, long)}</li>
 * <li>put float {@link #putFloat(Context, String, float)}</li>
 * <li>put boolean {@link #putBoolean(Context, String, boolean)}</li>
 * </ul>
 * <ul>
 * <strong>Get Value</strong>
 * <li>get string {@link #getString(Context, String)}, {@link #getString(Context, String, String)}</li>
 * <li>get int {@link #getInt(Context, String)}, {@link #getInt(Context, String, int)}</li>
 * <li>get long {@link #getLong(Context, String)}, {@link #getLong(Context, String, long)}</li>
 * <li>get float {@link #getFloat(Context, String)}, {@link #getFloat(Context, String, float)}</li>
 * <li>get boolean {@link #getBoolean(Context, String)}, {@link #getBoolean(Context, String, boolean)}</li>
 * </ul>
 * 
 * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2013-3-6
 */
public class PreferencesUtils {

    public static String PREFERENCE_NAME = "ChadAndroidCommon";

    /**
     * put string preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putString(Context context, String key, String value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        return editor.commit();
    }

    /**
     * get string preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or null. Throws ClassCastException if there is a preference with this
     *         name that is not a string
     * @see #getString(Context, String, String)
     */
    public static String getString(Context context, String key) {
        return getString(context, key, null);
    }

    /**
     * get string preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a string
     */
    public static String getString(Context context, String key, String defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getString(key, defaultValue);
    }

    /**
     * put int preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putInt(Context context, String key, int value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(key, value);
        return editor.commit();
    }

    /**
     * get int preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
     *         name that is not a int
     * @see #getInt(Context, String, int)
     */
    public static int getInt(Context context, String key) {
        return getInt(context, key, -1);
    }

    /**
     * get int preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a int
     */
    public static int getInt(Context context, String key, int defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getInt(key, defaultValue);
    }

    /**
     * put long preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putLong(Context context, String key, long value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(key, value);
        return editor.commit();
    }

    /**
     * get long preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
     *         name that is not a long
     * @see #getLong(Context, String, long)
     */
    public static long getLong(Context context, String key) {
        return getLong(context, key, -1);
    }

    /**
     * get long preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a long
     */
    public static long getLong(Context context, String key, long defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getLong(key, defaultValue);
    }

    /**
     * put float preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putFloat(Context context, String key, float value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putFloat(key, value);
        return editor.commit();
    }

    /**
     * get float preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
     *         name that is not a float
     * @see #getFloat(Context, String, float)
     */
    public static float getFloat(Context context, String key) {
        return getFloat(context, key, -1);
    }

    /**
     * get float preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a float
     */
    public static float getFloat(Context context, String key, float defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getFloat(key, defaultValue);
    }

    /**
     * put boolean preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putBoolean(Context context, String key, boolean value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(key, value);
        return editor.commit();
    }

    /**
     * get boolean preferences, default is false
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this
     *         name that is not a boolean
     * @see #getBoolean(Context, String, boolean)
     */
    public static boolean getBoolean(Context context, String key) {
        return getBoolean(context, key, false);
    }

    /**
     * get boolean preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a boolean
     */
    public static boolean getBoolean(Context context, String key, boolean defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getBoolean(key, defaultValue);
    }
}



你可能感兴趣的:(ym——Android从零开始(6)(Sdcard文件操作+pull解析+ SharedPreferences)(新))