【android, 3】3.操作数据保存到rom,sd卡上,sharedpreference的使用,pul解析xml

来源:互联网 发布:南昌市金域名都二手房 编辑:程序博客网 时间:2024/05/16 06:52

案例:用户的登录,并保存用户名密码到文件里,重新登录时回显用户名和密码。

一、编辑登录界面:

//总体为:线性竖直布局

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:orientation="vertical">

 

    <TextView  //标题

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/username"/> //内容

 

    <EditText  //输入框

        android:id="@+id/et_username"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:hint="@string/username"/>

 

    <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/password"/>

 

    <EditText

        android:id="@+id/et_password"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:inputType="textPassword"

        android:hint="@string/password"/>

 

    <RelativeLayout   //线性布局中包含的相对布局

        android:layout_width="fill_parent"

        android:layout_height="wrap_content">

 

        <Button

            android:id="@+id/bt_login"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_alignParentLeft="true"//靠父组件左

            android:text="@string/login"/>

       

       

        <CheckBox  //复选框

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="@string/remember"

            android:id="@+id/cb"

            android:layout_alignParentRight="true"  //靠父组件右

            />

    </RelativeLayout>

</LinearLayout>

 

二、在类中做相应操作:调用服务类将用户名密码写到文件中,读取用户信息显示到界面中

public classLoginActivity extendsActivity implements OnClickListener{

    private static final String TAG ="LoginActivity";

    private EditText et_username;

    private EditText et_password ;

    private Button bt_login;

    private CheckBox cb ;

    private FileService fileService;

 

    @Override

    public voidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

       

        //初始化组件

        et_username =  (EditText) this.findViewById(R.id.et_username);

        et_password =  (EditText) this.findViewById(R.id.et_password);

        bt_login =  (Button) this.findViewById(R.id.bt_login);

        cb  = (CheckBox) this.findViewById(R.id.cb);

       

        //注册监听

        bt_login.setOnClickListener(this);

       

        //初始化  FileService

        fileServicenew FileService(this);

       

        //为组件赋值:

        Map<String,String> map;

        try {

            map = fileService.getUserInfo("private.txt");

            et_username.setText(map.get("username"));

            et_password.setText(map.get("password"));

        } catch (Exceptione) {

            e.printStackTrace();

        }

    }

 

    /**

     * 点击执行的方法,参数是被点击的组件

     */

    public void onClick(Viewv) {

        switch (v.getId()){//获取组件id

        case R.id.bt_login:

            String  username =et_username.getText().toString();

            String  password =et_password.getText().toString();

            if(TextUtils.isEmpty(username)||TextUtils.isEmpty(password)){

                Toast.makeText(this, R.string.error,

Toast.LENGTH_SHORT).show();

                return;

            }

            if(cb.isChecked()){//判断checkbox是否选中

               

                Log.i(TAG,"选中" );

               

                //将用户名密码写到文件中

                try {

                    boolean b =fileService.saveToRom(username, password,

 "private.txt");

                    if(b){

                        Toast.makeText(this,"保存成功",

Toast.LENGTH_SHORT).show();

                       

                    }else{

                       

                        Toast.makeText(this,"保存失败",

 Toast.LENGTH_SHORT).show();

                    }

                } catch (Exceptione) {

                    Toast.makeText(this,"保存失败",

Toast.LENGTH_SHORT).show();

                    e.printStackTrace();

                }

               

            }else{

                Log.i(TAG,"未选中-----------------" );

               

            }

            break;

        }

    }

}

三、处理将用户信息写到文件中和回显的业务操作。

 

1、获取文件的输出流:上下文对象中的openFileOutput(文件名,模式)方法

文件会被输出到:/data/data/<当前包名>/files/filename

context.openFileOutput(filename,Context.MODE_PRIVATE);

 

2、获取文件的输入流:上下文对象中的openFileInput(文件名)方法

读取的文件流目录是:/data/data/<当前包名>/files/filename

public class FileService{ 

    private Context context;

   

    public FileService(Context context) {

        super();

        this.context = context;

    }

    //保存用户名密码的方法

    public boolean  saveToRom(String username , String password ,String filename)throws Exception{

       

        //使用context中的方法,以私有的方式打开一个文件的输出流 文件的名字叫 filename

        //Context.MODE_PRIVATE表示私有的模式,文件会被保存到:/data/data/<当前包名>/files/filename

        FileOutputStream fos = this.context.openFileOutput(filename, Context.MODE_PRIVATE);

        String result = username+":"+password;

        fos.write(result.getBytes());

        fos.flush();

        fos.close();

        return true;

    }

    //读取文件中的用户信息:

    public Map<String,String> getUserInfo(String fileName)throws Exception{

       

        Map<String,String> map = new HashMap<String, String>();

       

        //打开输入流.会读取/data/data/<当前包名>/files/filename 路径下的filename的文件

        FileInputStream fileInput = context.openFileInput(fileName);

       

        int len = 0 ;

        byte[] bys= new byte[1024];

        //字节数组输出流

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        while((len =fileInput.read(bys))!=-1){

            bos.write(bys, 0, len);

        }

        byte[] byteArray= bos.toByteArray();

       

        String info = new  String (byteArray);

       

        String[] split = info.split(":");

       

        map.put("username", split[0]);

        map.put("password", split[1]);

       

       

        return map;

    }

 

}

四、context.openFileOutput(filename,模式)中写文件的模式:

1、 Context.MODE_PRIVATE私有模式:表示其他程序是不可读,不可写该文件的。

this.context.openFileOutput(filename,Context.MODE_PRIVATE);

 

2、 Context.MODE_WORLD_READABLE:全局可写模式。其他程序可写不可读,

this.context.openFileOutput(filename,Context.MODE_WORLD_READABLE)

 

3、 Context.MODE_WORLD_WRITEABLE全局可读模式,其他程序可读不可写。

this.context.openFileOutput(filename, Context.MODE_WORLD_WRITEABLE)

 

4、想要全局可读可写文件,使用:

this.context.openFileOutput(filename,Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE);

5、 Context.MODE_APPEND追加模式写文件,

通过append的模式打开的文件 ,以后操作这个文件会以追加的方式把新的数据添加到文件的末尾.

相当于:私有的权限.

6、不同模式创建出不同文件的权限:

private.text  -rw-rw----

word.txt      -rw-rw-rw-

word_read.txt-rw-rw-r--

word_wirte    -rw-rw--w-

append        -rw-rw----

 

后面的内容是linux操作系统的文件访问权限

x代表的是可执行

第一个参数-文件

          d 文件夹

后面的9个参数可以把它分为3组

 

前三个参数   当前用户权限 

中间三个参数 当前用户所在的组权限

 

最后面三个参数 所有人权限。

改变权限使用的命令:

chmodchange mode

 例 chmod 777  文件名

 

五、保存数据到SD卡上:

1、 操作sd卡需要权限:在AndroidManifest.xml添加以下权限:

<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2、 保存到sd卡的操作:

①、不同的版本sd卡的根目录是不同的,

Environment.getExternalStorageDirectory()该方法是获取不同版本的根目录。

②、在操作sd卡之前,需要判断sd卡是否可用:

使用Environment.getExternalStorageState()获取状态:如果等于Environment.MEDIA_MOUNTED,表名sd卡可用。

③、注意:

判断sd卡是否可用需要权限:在AndroidManifest.xml添加以下权限:

<uses-permissionandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

 

例:

 

public booleansaveToSDcard(String username, String password,

            Stringfilename) throws Exception {

        // 2.1的平台 /sdcard/

        // File file = newFile("/mnt/sdcard/", filename);

        // 判断sd卡的状态

        // Environment.getExternalStorageState(); //获取外部存储设备的状态

 

        if(Environment.MEDIA_MOUNTED.equals(Environment

                .getExternalStorageState())) {

 

            Filefile = new File(Environment.getExternalStorageDirectory(),

                    filename);

            FileOutputStreamfos = new FileOutputStream(file);

            Stringresult = username + ":" + password;

            fos.write(result.getBytes());

            fos.flush();

            fos.close();

            returntrue;

        }else{

            Toast.makeText(context,"sd卡不可用", 0).show();

            returnfalse;

        }

    }

 

六、获取sd卡的相关信息:

1、操作sd卡需要两个权限:

 <uses-permissionandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2、操作sd卡:
public class DemoActivity extends Activity {

 

    public void onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        //获取sd卡的目录:

        File path =Environment.getExternalStorageDirectory();

       //

        StatFs stat = newStatFs(path.getPath());

        long blockSize = stat.getBlockSize();//每一个区块的大小

        long totalBlocks =stat.getBlockCount();  //所有区块

        long availableBlocks =stat.getAvailableBlocks(); // 所有可用区块

//获取sd卡总大小

      String totalsize =  Formatter.formatFileSize(this, totalBlocks *blockSize);

//获取sd卡的可用大小:

      String availablesize =  Formatter.formatFileSize(this,availableBlocks * blockSize);

//创建一个TextView 对象

      TextView tv = new TextView(this);

//设置值

      tv.setText("sd卡大小"+totalsize+"\n"+"可用空间"+availablesize);

//将控件设置在Activity 上,显示出来。

      setContentView(tv);

   

    }

}

七、保存和获取sharedpreference:中的数据。

1、保存数据到sharedpreference里面:

public boolean saveToSp(Stringusername, String password,

            Stringfilename){

        //获取SharePreferences对象,通过context.getSharedPreferences()方法:

//方法参数:(文件名称 ,保存模式)

        SharedPreferences sp  =

context.getSharedPreferences(filename, Context.MODE_PRIVATE);

//获取编辑对象:

        Editor editor = sp.edit();

        editor.putString("username",username);

        editor.putInt("myint", 5);

        editor.putBoolean("myboolean",false);

        editor.putString("password",password);

       

        editor.commit();// 把数据真正的提交到sharedpreference里面

        return true;

    }

 保存数据成功后,会在/data/data/<当前包名>/shared_prefs/spname.xml路径下,自动生成文件名为:指定的sp名称.xml 文件。

使用xml格式存放文件。

 

2、获取sharedpreference中的数据:

//获取对象:方法参数(sp名称,模式)

Sharedpreference sp =getSharedPreferences("userinfo", Context.MODE_PRIVATE);

//获取值, 方法参数(key的名称,当没有获取到显示的默认值)。

String username =sp.getString("username", "");

String password =sp.getString("password", "");

Boolean b = sp.getBoolean(“b”,true);

八、pull解析器读取xml文件

Pull解析器,回车换行算文本节点。

 

1、//以流的形式打开 xml文件:使用上下文中的getAssets().open()方法打开xml文件 获

//取输入流

InputStream is = getContext().getAssets().open("Person.xml");

//获取解析器

XmlPullParserparser = Xml.newPullParser();

parser.setInput(is,"utf-8");

List<Person>persons = null;

Personperson = null;

inttype = parser.getEventType(); //xml节点类型

//循环解析

while(type != XmlPullParser.END_DOCUMENT) {//不是xml文件的结束节点

 

    switch (type) {

        caseXmlPullParser.START_TAG://节点的开始标签

            if("persons".equals(parser.getName())) {

                persons= new ArrayList<Person>();

            } else if("person".equals(parser.getName())) {

                person= new Person();

//获取节点第一个属性

                Stringid = parser.getAttributeValue(0);                          person.setId(Integer.parseInt(id));

            } else if("name".equals(parser.getName())) {

                Stringname = parser.nextText();

                person.setName(name);

            } else if("age".equals(parser.getName())) {

                Stringage = parser.nextText();

                person.setAge(Integer.parseInt(age));

            }

                break;

        caseXmlPullParser.END_TAG://节点的结束标签

            if("person".equals(parser.getName())) {

                persons.add(person);

                person= null;

            }

            break;

 

        }

//下一个节点类型。

            type = parser.next();

        }

        returnpersons;

 

2、被解析的xml文件以及对应的节点类型:

//<?xml?>表示:xml文件的开头节点类型 XmlPullParser.START_DOCUMENT

<?xml version="1.0"encoding="UTF-8"?>

<persons>//开始标签 ,类型:XmlPullParser.START_TAG

    <personid="8"> // id="8" 属性     XmlPullParser.START_TAG

        <name>allen</name> // 文本节点

        <age>36</age>

    </person>  结束标签:类型为:   XmlPullParser.END_TAG

    <personid="28">

        <name>james</name>

        <age>25</age>

    </person>

</persons>     结束标签类型:XmlPullParser.END_TAG

 

最后 :xml文件的结尾    类型为:XmlPullParser.END_DOCUMENT

 

 

 

九、通过pull的xml序列号器生成xml文件:

例:将person对象的list集合生成xml文件。

 

//获取xml序列化器对象

XmlSerializer serializer =Xml.newSerializer();

//判断sd卡是否可用

if(Environment.MEDIA_MOUNTED.equals(

Environment.getExternalStorageState())){

//创建file对象;

        File file = new File(Environment.getExternalStorageDirectory(),

"person.xml");

         //创建输出流

        FileOutputStream fos = newFileOutputStream(file);

         //序列化器对象设置输出流, 参数:输出流对象,字符编码。

        serializer.setOutput(fos,"utf-8");

 

//写xml文件的文件头,即:<?xmlversion="1.0" encoding="UTF-8"?>

//参数(xml文件的编码,xml文件是否独立true为独立)

serializer.startDocument("utf-8", true);

//指定开始标签 ,参数(命名空间,标签的名称)

        serializer.startTag(null,"persons");

        for(Person person : persons){

            serializer.startTag(null,"person");

             //节点设置属性,参数(命名空间,属性名,属性值)

            serializer.attribute(null,"id", person.getId()+"");

            serializer.startTag(null,"name");

//设置文本节点,参数(文本内容)

            serializer.text(person.getName());

            serializer.endTag(null,"name");

           

            serializer.startTag(null,"age");

            serializer.text(person.getAge()+"");

            serializer.endTag(null,"age");

            //

            serializer.endTag(null,"person");

        }

        //指定结尾标签

        serializer.endTag(null,"persons");

        serializer.endDocument();//写xml文件的末尾

       

        fos.flush();//刷新输出流

        fos.close();

        return true;

        }else {

            returnfalse;

        }

 

 

0 0
原创粉丝点击