最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android數(shù)據(jù)存儲(chǔ)方式操作模式解析

 更新時(shí)間:2022年08月20日 17:18:58   作者:小熊迪迪  
這篇文章主要為大家介紹了Android數(shù)據(jù)存儲(chǔ)方式操作模式解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

SharedPreferences

在開(kāi)發(fā)過(guò)程中,數(shù)據(jù)存取是較為頻繁的,今天我們來(lái)了解下android幾種常見(jiàn)的數(shù)據(jù)存取方式。

在Android中,sharePreferences是一種輕量級(jí)的數(shù)據(jù)存儲(chǔ)方式,采用鍵值對(duì)的存儲(chǔ)方式,存儲(chǔ)少量數(shù)據(jù),支持基本類型的簡(jiǎn)單數(shù)據(jù)存儲(chǔ)。

基本用法

  • 根據(jù)Context獲取SharedPreferences對(duì)象
  • 利用edit()方法獲取Editor對(duì)象。
  • 通過(guò)Editor對(duì)象存儲(chǔ)key-value鍵值對(duì)數(shù)據(jù)。
  • 通過(guò)commit()方法提交數(shù)據(jù)。
public class MainActivity extends Activity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //獲取SharedPreferences對(duì)象
        Context ctx = MainActivity.this;  
        //第一個(gè)參數(shù)指定存儲(chǔ)文件名,第二個(gè)參數(shù)指定操作模式
        SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
        //存入數(shù)據(jù)
        Editor editor = sp.edit();
        editor.putString("STRING_KEY", "string");
        editor.putInt("INT_KEY", 0);
        editor.putBoolean("BOOLEAN_KEY", true);
        editor.commit();
        //返回STRING_KEY的值 設(shè)定默認(rèn)值
        Log.d("SP", sp.getString("STRING_KEY", "none"));
        //如果NOT_EXIST不存在,則返回值為"none"
        Log.d("SP", sp.getString("NOT_EXIST", "none"));
        //刪除指定數(shù)據(jù)
        editor.remove("STRING_KEY");
        editor.commit();
        //清空數(shù)據(jù)
        editor.clear();
        editor.commit();
     }
}

操作模式

  • MODE_PRIVATE 指定該SharedPreferences數(shù)據(jù)只能被本應(yīng)用程序讀、寫。這是默認(rèn)模式。
  • MODE_APPEND 該模式會(huì)檢查文件是否存在,存在就將數(shù)據(jù)寫到文件末尾,否則就創(chuàng)建新文件。
  • MODE_WORLD_READABLE指定該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序讀,但不能寫。該模式已棄用。
  • MODE_WORLD_WRITEABLE指定該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序?qū)憽?strong>該模式已棄用。

ContentProvider

基本概念

屬于Android四大組件之一,用于進(jìn)程間進(jìn)行數(shù)據(jù)交互,從而能夠讓其他的應(yīng)用保存或讀取此Content Provider的各種數(shù)據(jù)類型。簡(jiǎn)單來(lái)說(shuō),一個(gè)程序可以通過(guò)實(shí)現(xiàn)一個(gè)Content Provider的抽象接口將自己的數(shù)據(jù)暴露出去。外界根本看不到,也不用看到這個(gè)應(yīng)用暴露的數(shù)據(jù)在應(yīng)用當(dāng)中是如何存儲(chǔ)的,或者是用數(shù)據(jù)庫(kù)存儲(chǔ)還是用文件存儲(chǔ),還是通過(guò)網(wǎng)上獲得。

統(tǒng)一資源標(biāo)識(shí)符(URI)

content://com.example.myapplication.provider/tablename/1
  • content 主題名,URI前綴。
  • com.example.myapplication.provider 授權(quán)信息,Content Provider唯一標(biāo)識(shí)符。
  • tablename Content Provider 指向數(shù)據(jù)庫(kù)中的某個(gè)表名。
  • 1 表中某個(gè)記錄,若無(wú)指定,返回全部記錄。

基本使用

創(chuàng)建Content Provider

  • 創(chuàng)建一個(gè)繼承了ContentProvider父類的類
  • 定義一個(gè)名為CONTENT_URI,并且是public static final的Uri類型的類變量,必須為其指定一個(gè)唯一的字符串值,最好的方案是以類的全名稱。
  • 創(chuàng)建數(shù)據(jù)存儲(chǔ)系統(tǒng)。大多數(shù)Content Provider使用Android文件系統(tǒng)SQLite數(shù)據(jù)庫(kù)來(lái)保持?jǐn)?shù)據(jù),但是也可以以任何你想要的方式來(lái)存儲(chǔ)。但是,必須為其定義一個(gè)叫_id的列,它用來(lái)表示每條記錄的唯一性。

示例代碼(存儲(chǔ)用戶名稱并顯示用戶名稱,使用SQLite)

public class MyUsers {
    public static final String AUTHORITY  = “com.wissen.MyContentProvider”;
    // BaseColumn類中已經(jīng)包含了 _id字段
    public static final class User implements BaseColumns {
    public static final Uri CONTENT_URI  = Uri.parse(content://com.example.MyContentProvider”);
     // 表數(shù)據(jù)列
     public static final String  USER_NAME  = “USER_NAME”;
    }
}

如上代碼定義了Content Provider的Content_URI和數(shù)據(jù)列,然后再基于此定義Content Provider類。

package com.wissen.testApp.android;
public class MyContentProvider extends ContentProvider {
    private SQLiteDatabase sqlDB;
    private DatabaseHelper dbHelper;
    private static final String  DATABASE_NAME = “Users.db”;
    private static final int DATABASE_VERSION  = 1;
    private static final String TABLE_NAME   = “User”;
    private static final String TAG = “MyContentProvider”;
    //定義SQLite接口
    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
        //創(chuàng)建用于存儲(chǔ)數(shù)據(jù)的表
        db.execSQL(”Create table ” + TABLE_NAME + “( _id INTEGER PRIMARY KEY AUTOINCREMENT, USER_NAME TEXT);”);
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL(”DROP TABLE IF EXISTS ” + TABLE_NAME);
            onCreate(db);
        }
    }
    @Override
    public int delete(Uri uri, String s, String[] as) {
        return 0;
    }
    @Override
    public String getType(Uri uri) {
        return null;
    }
    @Override
    public Uri insert(Uri uri, ContentValues contentvalues) {
        sqlDB = dbHelper.getWritableDatabase();
        long rowId = sqlDB.insert(TABLE_NAME, “”, contentvalues);
        if (rowId > 0) {
            Uri rowUri = ContentUris.appendId(MyUsers.User.CONTENT_URI.buildUpon(), rowId).build();
            getContext().getContentResolver().notifyChange(rowUri, null);
            return rowUri;
        }
        throw new SQLException(”Failed to insert row into ” + uri);
    }
    @Override
    public boolean onCreate() {
        dbHelper = new DatabaseHelper(getContext());
        return (dbHelper == null) ? false : true;
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        qb.setTables(TABLE_NAME);
        Cursor c = qb.query(db, projection, selection, null, null, null, sortOrder);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }
    @Override
    public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
        return 0;
    }
}

如上所示,我們封裝了SQLite操作于Content Provider,是我們可以不再關(guān)注數(shù)據(jù)源的操作細(xì)節(jié),而直接使用Content Provider進(jìn)行數(shù)據(jù)的存取。

文件存儲(chǔ)

Android文件存儲(chǔ)可以用來(lái)存放大量數(shù)據(jù),如文本、圖片、音頻等。使用方法類似于java文件存儲(chǔ)。

基本使用

文件寫入

public void save() {
        try {
            FileOutputStream outStream=this.openFileOutput("a.txt",Context.MODE_WORLD_READABLE)
            outStream.write(text.getText().toString().getBytes());
            outStream.close();
            //成功消息提示
            Toast.makeText(MyActivity.this,"Saved",Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
 }

寫入文件若不存在,則會(huì)創(chuàng)建一個(gè)新的文件,保存在/data/data/files文件目錄下。

文件讀取

public void load()
{
    try {
        FileInputStream inStream=this.openFileInput("a.txt");
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        //分塊讀取
        byte[] buffer=new byte[1024];
        int length=-1;
    while((length=inStream.read(buffer))!=-1)   {
            stream.write(buffer,0,length);
        }
        stream.close();
        inStream.close();
        text.setText(stream.toString());
        Toast.makeText(MyActivity.this,"Loaded",Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

總結(jié)

本文簡(jiǎn)單介紹了Android幾個(gè)簡(jiǎn)單的數(shù)據(jù)存儲(chǔ)方式,包括簡(jiǎn)單數(shù)據(jù)存取,文件存儲(chǔ),以及如何封裝Content Provider,更多關(guān)于Android數(shù)據(jù)存儲(chǔ)操作模式的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

墨竹工卡县| 邵武市| 江山市| 仙居县| 民和| 华池县| 宜川县| 密山市| 和静县| 凤山县| 新干县| 资中县| 鄂托克前旗| 禄劝| 苗栗市| 云林县| 柏乡县| 德清县| 桦甸市| 潍坊市| 梅河口市| 军事| 凭祥市| 大足县| 平舆县| 乌拉特中旗| 霞浦县| 衡水市| 若尔盖县| 类乌齐县| 平舆县| 扎鲁特旗| 思南县| 祁门县| 塘沽区| 定州市| 濮阳市| 绥德县| 富裕县| 池州市| 常德市|