Android中的数据存取和IO <第一篇>
来源:互联网 发布:js 设置data属性 编辑:程序博客网 时间:2024/06/05 18:58
应用程序都会涉及到数据的输入、输出,android应用也不例外。Android中应用程序存储数据通常有两种模式:1,数据量少,格式简单(例如,字符串、标量),使用普通文本就好,可以使用Android系统提供的SharedPreferences保存;2、需要大量的数据存储访问,可以借助数据库,android系统提供了内置SQLite数据库,而且为访问数据库提供了方便的API。本片文章将会详细讲述如何在Android中使用数据库。
1、使用SharedPreferences访问key-value对和使用Editor写入数据
在一些小应用中,比如游戏的玩家积分(飞机大战之类的)、应用程序的配置信息(是否打开音效、振动等),使用SharedPreferences保存,这个方法保存的数据主要是简单类型的key-value对。
SharedPreferences提供的成员函数主要有三个:
》boolean contians(String key)
》abstract Map<String,?> getAll(); 获取SP数据里面的全部数据
》boolean getXxx(String key,xxx defVlaue) :获取key的值。
SharedPreferences并没有写入数据的能力,需要调用edit()方法来获取对应的Editor()。
》SharedPreferences.Editor clear() :清空SharedPreferences里面所有的额数据
》SharedPreferences.Editor putXxx(String key, xxx value):向SharedPreferences存入key值
》boolean 层哦秘密他() :当完成editot编译,提交改方法,通常写在末尾。
SharedPreferences是一个接口,程序无法直接创建SharedPreferences实例,需要通过Context提供getSharedPreferences(Stirng name,int mode)来创建实例。
第二个参数如下:
》Context.MODE_PRIVATE :指定改数据只能被本程序读写
》Context.MODE_WORLD_READABLE:可以被其他程序读,但不能写
》Context.MODE_WORLD_WRITEABLE:课被其他读写。
例程如下:提供两个按钮,一个写入数据,另一个读取写入的数据。
1、activity下的.java文件如下:
package org.crazyit.io;import java.text.SimpleDateFormat;import java.util.Date;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;/** * Description: * <br/>site: <a href="http://www.crazyit.org">crazyit.org</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */public class SharedPreferencesTest extends Activity{SharedPreferences preferences;SharedPreferences.Editor editor;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);// 创建SharedPreferences实例,名字、可读preferences = getSharedPreferences("crazyit", MODE_WORLD_READABLE);editor = preferences.edit();Button read = (Button) findViewById(R.id.read);Button write = (Button) findViewById(R.id.write);read.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0){//获取time的字符串String time = preferences.getString("time", null);//读取int的随机数int randNum = preferences.getInt("random", 0);String result = time == null ? //?判断"您暂时还未写入数据": "写入时间:" + time + "\n上次随机生成的随机数为:" + randNum;//toast提示Toast.makeText(SharedPreferencesTest.this , result , Toast.LENGTH_LONG).show();}});write.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0){SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 "+ "hh:mm:ss");// 存入当前时间editor.putString("time", sdf.format(new Date()));// 存入随机数editor.putInt("random", (int) (Math.random() * 100));// 提交数据editor.commit();}});}}
2、res下面的布局文件:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center_horizontal"><Button android:id="@+id/write"android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/write"/><Button android:id="@+id/read"android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/read"/></LinearLayout>
3、AVD调试结果如下:
打开DDMS调试可以知道,sharedpreferences数据总是保存在/data/data/<package name>/shared_prefs目录下面以.xml形式保存。
2、File存储
Java提供了一套完整的IO流体系,包括FileInPutSream、FileOutPutStream,通过这些IO流来访问磁盘文件,android同样支持以这种方式来访问手机存储器的文件。
Context提供了两种方法来打开文件应用程序下的数据文件IO流:
》 public FileInputStream openFileInput (String name) :打开输入流文件name
》 public FileOutputStream openFileOutput (String name, int mode) :打开输出流文件name
这里解释一下输入流和输出流:输入流指的是从硬盘等存储器中读数据到内存中,软件在内存中运行;输出流指的是从内存中读数据到外部存储器中。
mode参数主要有:
》MODE_PRIVATE :指定改数据只能被本程序读写
》MODE_APPEND :以追加方式打开,可向该文件夹中追加内容
》MODE_WORLD_READABLE:可以被其他程序读,但不能写
》MODE_WORLD_WRITEABLE:可被其他读写。
1、activity下的.java
package wqt.list.filereadwrite;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.PrintStream;import android.os.Bundle;import android.app.Activity;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity {final String File_name="Read_Write";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button read=(Button)findViewById(R.id.read);Button write=(Button)findViewById(R.id.write);final EditText edit1=(EditText) findViewById(R.id.edit1);final EditText edit2=(EditText) findViewById(R.id.edit2);write.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub//将wdit1中的内容写入到文件中write(edit1.getText().toString()); //write函数在下面需要定义edit1.setText("");}});read.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubedit2.setText(read()); //read函数需要在下面定义}});}private String read(){try{//打开文件输入流FileInputStream fis =openFileInput(File_name );byte[] buff = new byte[1024];int hadRead =0;StringBuilder sb = new StringBuilder("");while( (hadRead = fis.read(buff)) > 0){sb.append(new String(buff,0,hadRead));} return sb.toString();}catch(Exception e){e.printStackTrace();}return null;}private void write(String content){try{//使用追加模式打开文件输出流FileOutputStream fos = openFileOutput(File_name, MODE_APPEND);PrintStream ps=new PrintStream(fos);ps.println(content);ps.close();}catch(Exception e){e.printStackTrace();}}}
2.res下的layout文件.xml<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"> <Button android:id="@+id/write" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/write"/> <EditText android:id="@+id/edit1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:lines="4"/> <Button android:id="@+id/read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/read"/> <EditText android:id="@+id/edit2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:lines="4" android:editable="false" android:cursorVisible="false"/></LinearLayout>
3、AVD调试:
- Android中的数据存取和IO <第一篇>
- Android中的数据存取三种方式
- android中的数据存取 之 SQLite
- android中的数据存取 之 File
- 第九章:Android中的数据存取
- Visual+C#+2005文件IO和数据存取秘诀 目录
- Android 中的UI第一篇:Common Layout
- Android 数据存取
- Android 存取数据
- Android中数据存取
- Android数据存取
- Android数据存取
- Android的数据存取
- android之数据存取
- android 存取数据。
- Android数据存取
- Android 中的数据存取方式之一: Preference(配置)
- Android 中的数据存取方式之一: Preference(配置) .
- Spring MVC
- 【C++学习之路】继承、虚函数的练习题目
- 【python系列】matplotlib简单画图subplot
- PLSQL数据导入导出问题
- 学习和使用SAS的一点感想(京剧)
- Android中的数据存取和IO <第一篇>
- ASP.Net中文件下载的两种方法
- spring配置aop的总结
- WTL Splitters and Pane Containers
- PAT 1046. Shortest Distance (20)
- linux下vi命令大全
- 将ffmpeg编入motion
- 容斥原理应用
- android库SwipeListView的使用