Android 數據存儲方法
數據存儲在開發中是使用最頻繁的,在這里我介紹Android平臺中實現數據存儲的5種方式:
1:使用SharedPreferences存儲數據;
2:File存儲數據;
3:SQLite數據庫儲存數據;
4:使用ContentProvider儲存數據;
5:網絡儲存數據;**
網絡儲存方式,需要與Android網絡數據包打交道,關于Android 網絡數據包的詳細說明,請閱讀Android SDK引用了Java SDK的哪些package。
ContentProvider簡介:android四大組件之一,管理android以結構化方式存放的數據,以相對安全的方式封裝數據(表)并提供簡易的處理機制和統一的訪問接口供其他程序調用.
但注意ContentProvider它也只是一個中間人,真正操作的數據源可能是數據庫,也可以是文件、xml或網絡等其他存儲方式。
URL(統一資源標識符):代表要操作的數據,可以用來標識每個ContentProvider,這樣你就可以通過指定的URI找到想要的ContentProvider,從中獲取或修改數據。
在Android中URI的格式如下圖所示:
A schema,已經由Android所規定為:content://.
B 主機名(Authority),是URI的授權部分,是唯一標識符,用來定位ContentProvider。
C部分和D部分:是每個ContentProvider內部的路徑部分
C 指向一個對象集合,一般用表的名字,如果沒有指定D部分,則返回全部記錄。
D 指向特定的記錄,這里表示操作user表id為7的記錄。如果要操作user表中id為aname7/n法me即可。
主要方法
public boolean onCreate()
ContentProvider創建后 或 打開系統后其它應用第一次訪問該CorovidntentPer時調用。
public Uri insert(Uri uri, ContentValues values) 外部應用向Contvider中添加數據.
public int delete(Uri uri, String selection, String[] selectionArgs) 外部應用從ContentProvider刪除數據。
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs):
外部應用更新ContentProvider中的數據。
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
供外部應用從ContentProvider中更取數據 .
數據庫存儲方法:
代碼示例:
public class NoteActivity extends Activity implements View.OnClickListener,OnItemClickListener
,OnItemLongClickListener{
public static final String ACTION_NOTE_NEW = "action.note.new";
public static final String ACTION_NOTE_EDIT = "action.note.edit";
private ListView mListView;
private NoteAdapter mAdapter;
private ArrayList<Note> mNoteList;
private NoteDao mDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
initDate();
initViews();
}
@Override
protected void onResume() {
super.onResume();
mNoteList = mDao.queryAll();
mAdapter = new NoteAdapter(mNoteList, this);
mListView.setAdapter(mAdapter);
}
private void initViews() {
mListView = (ListView)findViewById(R.id.listView);
mListView.setOnItemClickListener(this);
mListView.setOnItemLongClickListener(this);
findViewById(R.id.btn_add).setOnClickListener(this);
}
private void initDate() {
mDao = new NoteDao(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
Intent intent = new Intent();
intent.setClass(this, NoteEditActivity.class);
intent.setAction(ACTION_NOTE_NEW);
startActivity(intent);
break;
default:
break;
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Note note = mNoteList.get(arg2);
Intent intent = new Intent();
intent.setClass(this, NoteEditActivity.class);
intent.setAction(ACTION_NOTE_EDIT);
intent.putExtra("id", arg3);
intent.putExtra("title", note.getTitle());
intent.putExtra("content", note.getContent());
startActivity(intent);
}
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
final long id = arg3;
new AlertDialog.Builder(this)
.setTitle("刪除")
.setMessage("確定刪除此記事?")
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
pbulic void } onClick(DialogInterface dialog, int which) {
mDao.delete(id);
} onResume ();
})
.setNegativeButton("取消", null)
.create().show
();
return true;
}
}
public class NoteAdapter extends BaseAdapter{
private ArrayList<Note> mNoteList;
private LayoutInflater mInflater;
public NoteAdapter(ArrayList<Note> list, Context context){
mNoteList = list;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
if (mNoteList != null) {
return mNoteList.size();
}
return 0;
}
@Override
public Object getItem(int position) {
if (mNoteList != null) {
return mNoteList.get(position);
}
return null;
}
@Override
public long getItemId(int position) {
if (mNoteList != null) {
Note note = mNoteList.get(position);
return note.getId();
}
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_note_item, null);
}
TextView txtTitle = (TextView)convertView.findViewById(R.id.txt_title);
TextView txtContent = (TextView)convertView.findViewById(R.id.txt_content);
TextView txtTime = (TextView)convertView.findViewByime);
Note note = mNoteList.get(position);
String title = note.getTitle();
String content = note.getContent();
long time = note.getTime();
txtTitle.setText(title);
txtContent.setText(content);
txtTime.setText(String.valueOf(time));
return convertView;
}
}
public class NoteDao implements NoteTable {
private SQLiteDatabase mDB;
public NoteDao(Context context){
mDB = MyDBUtil.getInstance(context).getDB();
}
public long add(Note note){
//參數檢查
if (note == null) {
return -1;
}
//參數轉化
ContentValues values = new ContentValues();
values.put(TITLE, note.getTitle());
values.put(CONTENT, note.getContent());
values.put(TIME, note.getTime());
//入庫
long id = mDB.insert(TABLE_NAME, null, values);
return id;
}
public ArrayList<Note> queryAll(){
ArrayList<Note> list = new ArrayList<Note>();
Cursor cursor = mDB.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
long id = cursor.getLong(0);
String title = cursor.getString(1);
String content = cursor.getString(2);
long time = cursor.getLong(3);
Note note = new Note();
note.setId(id);
note.setTitle(title);
note.setContent(content);
note.setTime(time);
list.add(note);
} while (cursor.moveToNext());
cursor.close();
}
return list;
}
public int update(long id, Note note){
//參數檢查
if (id < 0 || note == null) {
return -1;
}
String where = ID + "=?";
String[] args = new String[]{String.valueOf(id)};
//參數轉化
ContentValues values = new ContentValues();
values.put(TITLE, note.getTitle());
values.put(CONTENT, note.getContent());
values.put(TIME, note.getTime());
int count = mDB.update(TABLE_NAME, values, where, args);
return count;
}
public int delete(long id){
String where = ID + "=?";
String[] args = new String[]{String.valueOf(id)};
int count = mDB.delete(TABLE_NAME, where, args);
return count;
}
}
public interface NoteTable {
public static final String TABLE_NAME = "note";
public static final String ID = "_id";
public static final String TITLE = "title";
public static final String CONTENT = "content";
public static final String TIME = "time";
public static final String SQL_CREATE = new StringBuilder()
.append}
"CREATE TABLE IF NO
T EXISTS ").append(TABLE_NAME)
.append("(")
.append(ID).append(" INTEGER PRIMARY KEY,")
.append(TITLE).append(" TEXT,")
.append(CONTENT).append(" TEXT,")
.append(TIME).append(" INTEGER")
.append(");")
.toString();
} public class MyDBUtil {
public static final String DB_NAME = "A25";
public static final int DB_VER = 1;
private SQLiteDatabase mDB;
private MyHelper mHelper;
private static MyDBUtil mInstance;
private MyDBUtil(Context context){
mHelper = new MyHelper(context);
mDB = mHelper.getWritableDatabase();
}
public static MyDBUtil getInstance(Context context){
if (mInstance == null) {
mInstance = new MyDBUtil(context);
}
return mInstance;
}
public SQLiteDatabase getDB(){
return mDB;
}
@Override
protected void finalize() throws Throwable {
mHelper.close();
mDB.close();
super.finalize();
}
class MyHelper extends SQLiteOpenHelpe SharedPreferencest context) {
super(context, DB_NAME, null, DB_VER);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(NoteTable.SQL_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
SharedPreferences的本質是基于XML文件存儲key-value鍵值對數據,通常用來存儲一些簡單的配置信息,用Sqlite數據庫來存放并不劃算,因為數據庫連接跟操作等耗時大大影響了程序的效率。其存儲位置在/data/data/<包名>/shared_prefs目錄下。
另外SharedPreferences只能保存簡單類型的數據,例如,String、int等。一般會將復雜類型的數據轉換成Base64編碼,然后將轉換后的數據以字符串的形式保存在 XML文件中,再用SharedPreferences保存。
使用SharedPreferences保存key-value對的步驟如下:
(1)使用Activity類的getSharedPreferences方法獲得SharedPreferences對象,其中存儲key-value的。
件的名稱由getSharedPreferences方法的第一個參數指定,第二個參數指定訪問應用程序私有文件的權限。
(2)使用SharedPreferences接口的edit獲得SharedPreferences.Editor對象。
(3)通過SharedPreferences.Editor接口的putXxx方法保存key-value對。其中Xxx表示不同的數據類型。例如:字符串類型的value需要用putString方法。
(4)通過SharedPreferences.Editor接口的commit方法保存key-value對。commit方法相當于數據庫事務中的提交(commit)操作。
來自:http://blog.csdn.net/google_huchun/article/details/53713265