【android基础】数据存储

SharedPreference  [共享偏好]

是一种轻量级的数据存储方法.保存在data/data/ [packname] /shared_prefs 目录中

SharedPreferences sp = getSharedPreferences(" spname" , MODE_PRIVATE);  
//如果spname不存在,则创建.存在则读入文件

读操作

String name =sp.getString("Name","TOM");   //读取失败时,放入TOM值
int age=sp.getInt("Age",20);               //读取失败时,放入20
float height=sp.getFloat("Heigt",1.81f);     //读取失败时,放入1.81f

写操作

sp.Editor  editor=sp.edit();           //新建编辑器
editor.putString("Name","TOM");
editor.putInt("Age",20);
editor.putFloat("Heigt",1.81f);
editor.commit();                        //提交,不提交是无效果的


當然,也可以跨應用程序获取SharePreference.

try{
     Context  c=this.createPackageContext ("com.example.aaaActivity" ,CONTEXT_IGNORE_SECURITY);
   }catch (NameNotFoundException e)  {
            e.printStackTrace();
     }
 SharedPreference sp= c. getSharedPreferences("spname" ,MODE);
//MODE=MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE 要其他程序也能读写

FileStream  [文件流]

其實跟上面的差不多,保存在data/data/ [packname] /files 目录中

写入

FileOutputStream fos =openFileOutput("filename " ,Context.MODE_PRIVATE);//左边这个是新建,MODE_APPEND是加入数据的模式
String text="some data"
fos.write(text.getBytes());
fos.flush();  //写入量少的时候会保存在缓冲区一次输出的,所以在close()前调用一次flush();
fos.close();
读取
FileInputStream fis=openFileInput("filename");
byte[]readBytes =new byte[fis.available()];
while(fis.read(readBytes)!=-1)  {  }
String  text=new String(readBytes);

上面两个最好放在try { } catch IOException 里面


如果是读取资源文件的话

Resources resources =this.getResources();
InputStream inputStream=null;
 inputStream =resources.openRawResource(R.raw.raw_file);
    byte[] reader=new byte[ inputStream.available() ];
    while(inputStream.read (reader) !=-1 ){}
   

XmlPullParser    [XmlPull解释器]

XmlPullParser parser =resources.getXml(R.xml.abc);     //定义一个解释器,并获取资源
String msg="  ";
try{
    while( parser.next() !=  XmlPullParser.END_DOCUMENT){
       String people=parser.getName();
     String   name=null;
      String  age=null;
      if(people!=null)  &&  people.equals("person") ){
      int   count=parser.getAttributeCount();                    //获取元素数量
       for(int i=0; i< count ; i++){
                String attrName=  parser. getAttributeName(i) ;     //获取元素名称
                String  attrValue =parser.getAttributeValue(i);     //获取元素数值
                 if((attrName  != null)  && attrName.equals("name"))  name =attrValue;
   }
    msg+="姓名:" + name  +",年龄:" + age+ ",身高:"+ height  +"\n";
   }
}catch (Exception e)    {}
START_TAG          读取到标签开始标志

END_TAG              读取到标签结束标志

TEXT                      读取文本内容

END_DOCUMENT           文档结尾


SQLite        [SQL数据库]

也是轻量级的储存.保存在data/data/ [ package name] / databases

封装一个数据库的类

1.创建或者打开一个数据库 

sqlOpenHelper.onCreate(SQLiteDatabase){}    
//或者是 db.openOrCreateDatabases(DB_NAME , MODE, null);
2.使用SQL语句创建一个表
SQLiteDatabase.execSQL(" create table AAA ( colum1, colum2 );");

3.增

SQLiteDatabase.insert(TABLE_NAME,null,values);
//其中values是一行的数据,所以用contextview来承载
4.删
SQLiteDatabase.delete(TABALE_NAME, id, null);
5.改
SQLiteDatabase.uodate(TABLE_NAME,updateValue, id ,null);
6.查
SQLiteDatabase.query( String table(表名), String[] columns(列名), String selection(条件)  , String[] selectionArgs(代替条件中的"?") ,String groupBy(分组方式) ,  String having (定义组的过滤器)  , String orderBy(排序方式)    ) ;    //因此要用到游标
7.关闭数据库
SQLiteDatabase.close();

例子:

public class DBAdapter{
    private final Context context;  
    public void DBAdapter(Context context){
       rhis.context=context;
   }
  
private SQLiteDatebase db;    //声明一个SQLDB的类,这个类封装了很多方法,而且基本不直接调用.
private  ABCD    abcd;           //上面说过不直接调用,所以创建一个类,用来打开和关闭数据库.
//这个类名字随意了,但是必须是继承SQLiteOpenHelpder

   //打开数据库
   public void open() throw SQLiteException{
        abcd=new ABCD(context, "people.db" , null ,DB_VERSION);
         try{
             db=abcd.getWritableDatabase();     //获取可读写
           }catch (SQLiteException  ex){
              db=abcd.getReadableDatabase();    //磁盘已满时获取只读
          }
      }
    /*直接打开或者创建数据库
     public void  created(){
        db.openOrCreateDatabase("people.db", context.MODE_PRIVATE , null);
        db.execsSQL(创建表的SQL语句);
     }                   */
   //数据操作
   public long insert (People people){   //插入
          ContentValues newValues =new ContentValues();     //新建一个ContentValues 对象
           newValues.put("name" ,  people.name);                    //列名, 以及其数值
           newValues.put("age" ,  people.age); 
            newValues.put("heigjt" ,  people.height);
           return   db.insert("peopleinfo",null, newValues);    //插入的表名  ,null表示要替换的地方,   第三个是新插入的行
     }
   //删除
    public long deleteAllData(){
        return  db.delete("peopleinfo",null,null);      
      }     //第一个参数是表名, 第二个是删除条件
  public long deleteOnedate( long id){
      return db.delete("peopleinfo","id="+id,null);
     }
  //更新 
 public long updateOneData (long id,People people){   
          ContentValues newValues =new ContentValues();     //新建一个ContentValues 对象
           newValues.put("name" ,  people.name);                    //列名, 以及其数值
           newValues.put("age" ,  people.age); 
            newValues.put("heigjt" ,  people.height);
           return   db.update("peopleinfo",newValues,"id= "+id,null);    //插入的表名  , 第三个更新的条件
     }
//查询
 public People[ ]  getAllData(){
         Cursor  results=db.query(   "peopleinfo" ,  new String[ ]{ "_id" ,"name","age","height" }  ,null,null,null,null,null);
          return  ConvertToPeople(results);   //要求返回的是数组,所以要定义一个游标集合Cursor
}

 public People[ ]  getOneData(long id){
         Cursor  results=db.query(   "peopleinfo" ,  new String[ ]{ "_id" ,"name","age","height" }  ,"_id="+id,null,null,null,null);
          return  ConvertToPeople(results);  
}


 private Peoplep[ ] ConvertToPeople(Cursor cursor){
     int resultCount=cursor .getCount();
     if(resultCounts==0 || !cursor.moveToFirst()) {  return null;}
     People[ ]  people =new People[resultCounts];
     for(int i=0;  i<resultCounts ; i++)  {
          peoples[ i ] =new  People();
          people[i].ID =cursor.getInt ( 0 );
         people[i].Name=cursor.getString(cursor.getColumnIndex("name"));
       cursor.moveToNext();
     }
   return  peoples;
    }

 
   //关闭,可直接调用SQLiteDatabase的函数
    public void close(){
      if(db!=null) {
            db.close();
            db=null;
         }      
         }
}

private static class ABCD extends SQLiteOpenHelper{
      public ABCD (Context context ,  String  name  ,  CursorFactory factory  ,  int version ){
               super(context,  name ,factory,  version); 
               }
    @Override
    public void onCreated(SQLitteDatabase  db){
               db.execSQL("create table peopleinfo (
                                         _id  intergerprimary  key  autoincrement, 
                                             name  text not null , 
                                              age  integer  , 
                                               height  float); " );                       //sql的创表语句啦
                }
     @Override
    public void onUpgrade(SQLitteDatabase  db,int oldVersion,  int  newVersion){
               db.execSQL("DROP TABLE IF EXISTS   peopleinfo");       //sql的创表语句啦
               onCreate(db) ;
              }
    }

数据共享

就是使用uri来管理数据了

首先建立ContentProvider

public class Abc extends ContentProvider{

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}
}
2.构造UriMatcher ,用来判断是单条数据还是多条数据
pribate static final UriMatcher uriMatcher;  
static{                  //静态构造函数
          uriMactcher =new  UriMatcher( UriMatcher.NO_MATCH );    //建立一个uriMatcher,暂没匹配
        
          /* 添加新的匹配项
           public void addURI(String authority,  String  path , int  code); 
          参数1:授权者名称   参数2: 路径,其中下面有#的是单条数据,#表示任意数字,  参数三:返回代码*/
         uriMacher.addURI("com.example.peopleprovider","people/#",1); 
         uriMatcher.addURI("com.example.peopleprovider","people",2);
   }
 //匹配
    switch(uriMatcher.match(uri)){
            case 1: //
            case 2:  //
          }
3.在Manifest注册 ,在<application >的节点下
<provider android:name=".PeopleProvider"
                   android:authorities="com.example.peopleprovider" />
4.使用数据提供者 ,先定义一个 ContentResolver
ContentResolver rs= getContentResolver( );
5.数据操作

  查询

Cursor cursor  =rs.query(Uri uri , String[ ] projection, String selection , String[ ] selectionArgs,  String sortOrder);

  URI是通用资源标识符,ContentProvider中的uri必须是: content:// <授权名> / <路径> / <id>

   比如说上面要查询ID为2的数据. 则是 Uri uri=Uri.parse("content : // com.example.peopleprovider / people /2");

 第二个参数是数据项,就是new String[ ] {"_id","name","age","height"}; 那样的

  总之语法和SQLite差不多.

添加

Uri newUri = rs.insert(uri , values);   //添加单条数据,values 的类型是ContentValues
int count=rs. bultInsert(uri, arrayValues);  //一次添加多条数据,arrayValues是ContentValues[ ]
删除
int result =rs.delete(uri , selection ,null); 

 uri是指定要删除的, selection则是条件,比如说String selection="_id>4" 则表示删除大于4的数据项

更新

int result =rs.resolver.update(uri ,values.null, null);
uri指定项,valuse更新值..第三个是selection







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值