Android提供了5種方式存儲數據:


--使用SharedPreferences存儲數據;

--文件存儲數據;

--SQLite數據庫存儲數據;

--使用ContentProvider存儲數據;

--網絡存儲數據;


一:使用SharedPreferences存儲數據

首先說明SharedPreferences存儲方式,它是Android提供的用來存儲一些簡單配置信息的一種機制,
例如:登錄用戶的用戶名與密碼。其采用了Map數據結構來存儲數據,以鍵值的方式存儲,可以簡單的讀取與寫入,具體實例如下:

void ReadSharedPreferences(){
  String strName,strPassword;
  SharedPreferences   user = getSharedPreferences(“user_info”,0);
  strName = user.getString(“NAME”,””);
  strPassword = user getString(“PASSWORD”,””);
}

void WriteSharedPreferences(String strName,String strPassword){
  SharedPreferences   user = getSharedPreferences(“user_info”,0);
  uer.edit();
  user.putString(“NAME”, strName);
  user.putString(“PASSWORD” ,strPassword);
  user.commit();
}

數據讀取與寫入的方法都非常簡單,只是在寫入的時候有些區別:
先調用edit()使其處於編輯狀態,然后才能修改數據,最后使用commit()提交修改的數據。
實際上SharedPreferences是采用了XML格式將數據存儲到設備中,在DDMS中的File Explorer中的/data/data/<package name>/shares_prefs下。
以上面的數據存儲結果為例,打開后可以看到一個user_info.xml的文件,打開后可以看到:

<?xml version=”1.0″ encoding=”UTF-8″?>
<map>
  <string name=”NAME”>moandroid</string>
  <string name=” PASSWORD”>SharedPreferences</string>
</map>
使用SharedPreferences是有些限制的:只能在同一個包內使用,不能在不同的包之間使用。
 

實例:

/Chapter09_Data_01/src/com/amaker/test/MainActivity.java

代碼

package com.amaker.test;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
    private EditText myEditText;
    private Button b1;
    private static final String TEMP_SMS="temp_sms";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myEditText = (EditText)findViewById(R.id.EditText01);
        b1 = (Button)findViewById(R.id.Button01);
        
        SharedPreferences pre = getSharedPreferences(TEMP_SMS, MODE_WORLD_READABLE);
        String content = pre.getString("sms_content", "");
        myEditText.setText(content);
        
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        SharedPreferences.Editor editor = getSharedPreferences(TEMP_SMS, MODE_WORLD_WRITEABLE).edit();
        editor.putString("sms_content", myEditText.getText().toString());
        editor.commit();
    }
}
View Code

 

/Chapter09_Data_01/res/layout/main.xml

代碼

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:text="Preference Test"/>
<EditText 
android:text="" 
android:id="@+id/EditText01" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content"
android:height="180px"
></EditText>
<Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send"></Button>
</LinearLayout>
View Code

 

/Chapter09_Data_01/AndroidManifest.xml

代碼

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.amaker.test"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="3" />

</manifest>
View Code

 

 
 
二:文件存儲數據
文件存儲方式是一種較常用的方法,在Android中讀取/寫入文件的方法,與Java中實現I/O的程序是完全一樣的,
提供了openFileInput()和openFileOutput()方法來讀取設備上的文件。FilterInputStream, FilterOutputStream等可以到Java io package說明中去詳細學習,不再此詳細說明,具體實例如下:

String fn = “moandroid.log”;
FileInputStream fis = openFileInput(fn);
FileOutputStream fos = openFileOutput(fn,Context.MODE_PRIVATE);
除此之外,Android還提供了其他函數來操作文件,詳細說明請閱讀android sdk


三:網絡存儲數據
網絡存儲方式,需要與Android 網絡數據包打交道,關於Android 網絡數據包的詳細說明,請閱讀Android SDK引用了Java SDK的哪些package?。
四:ContentProvider

1、ContentProvider簡介
當應用繼承ContentProvider類,並重寫該類用於提供數據和存儲數據的方法,就可以向其他應用共享其數據。雖然使用其他方法也可以對外共享數據,但數據訪問方式會因數據存儲的方式而不同,如:采用文件方式對外共享數據,需要進行文件操作讀寫數據;采用sharedpreferences共享數據,需要使用sharedpreferences API讀寫數據。而使用ContentProvider共享數據的好處是統一了數據訪問方式。?

2、Uri類簡介
Uri代表了要操作的數據,Uri主要包含了兩部分信息:1.需要操作的ContentProvider ,2.對ContentProvider中的什么數據進行操作,一個Uri由以下幾部分組成:

1.scheme:ContentProvider(內容提供者)的scheme已經由Android所規定為:content://。

2.主機名(或Authority):用於唯一標識這個ContentProvider,外部調用者可以根據這個標識來找到它。

3.路徑(path):可以用來表示我們要操作的數據,路徑的構建應根據業務而定,如下:

要操作contact表中id為10的記錄,可以構建這樣的路徑:/contact/10
要操作contact表中id為10的記錄的name字段, contact/10/name
要操作contact表中的所有記錄,可以構建這樣的路徑:/contact?
要操作的數據不一定來自數據庫,也可以是文件等他存儲方式,如下:
要操作xml文件中contact節點下的name節點,可以構建這樣的路徑:/contact/name
如果要把一個字符串轉換成Uri,可以使用Uri類中的parse()方法,如下:
Uri uri = Uri.parse("content://com.changcheng.provider.contactprovider/contact")

3、UriMatcher、ContentUrist和ContentResolver簡介

因為Uri代表了要操作的數據,所以我們很經常需要解析Uri,並從Uri中獲取數據。Android系統提供了兩個用於操作Uri的工具類,分別為UriMatcher 和ContentUris 。掌握它們的使用,會便於我們的開發工作。

UriMatcher:用於匹配Uri,它的用法如下:

1.首先把你需要匹配Uri路徑全部給注冊上,如下:
//常量UriMatcher.NO_MATCH表示不匹配任何路徑的返回碼(-1)。
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
//如果match()方法匹配content://com.changcheng.sqlite.provider.contactprovider/contact路徑,返回匹配碼為1
uriMatcher.addURI(“com.changcheng.sqlite.provider.contactprovider”, “contact”, 1);//添加需要匹配uri,如果匹配就會返回匹配碼
//如果match()方法匹配 content://com.changcheng.sqlite.provider.contactprovider/contact/230路徑,返回匹配碼為2
uriMatcher.addURI(“com.changcheng.sqlite.provider.contactprovider”, “contact/#”, 2);//#號為通配符

2.注冊完需要匹配的Uri后,就可以使用uriMatcher.match(uri)方法對輸入的Uri進行匹配,如果匹配就返回匹配碼,匹配碼是調用addURI()方法傳入的第三個參數,假設匹配content://com.changcheng.sqlite.provider.contactprovider/contact路徑,返回的匹配碼為1。
ContentUris:用於獲取Uri路徑后面的ID部分,它有兩個比較實用的方法:
withAppendedId(uri, id)用於為路徑加上ID部分
parseId(uri)方法用於從路徑中獲取ID部分

ContentResolver:當外部應用需要對ContentProvider中的數據進行添加、刪除、修改和查詢操作時,可以使用ContentResolver 類來完成,要獲取ContentResolver 對象,可以使用Activity提供的getContentResolver()方法。 ContentResolver使用insert、delete、update、query方法,來操作數據。
 
五:總結說明
以上5中存儲方式,在以后的開發過程中,根據設計目標、性能需求、空間需求等找到合適的數據存儲方式。
Android 中的數據存儲都是私有的,其他應用程序都是無法訪問的,除非通過ContentResolver獲取其他程序共享的數據。
采用文件方式對外共享數據,需要進行文件操作讀寫數據;采用sharedpreferences共享數據,需要使用sharedpreferences API讀寫數據
而使用ContentProvider共享數據的好處是統一了數據訪問方式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM