Android 数据存储方法
liuhui029
8年前
<p>数据存储在开发中是使用最频繁的,在这里我介绍Android平台中实现数据存储的5种方式:</p> <p>1:使用SharedPreferences存储数据;</p> <p>2:File存储数据;</p> <p>3:SQLite数据库储存数据;</p> <p>4:使用ContentProvider储存数据;</p> <p>5:网络储存数据;**</p> <p>网络储存方式,需要与Android网络数据包打交道,关于Android 网络数据包的详细说明,请阅读Android SDK引用了Java SDK的哪些package。</p> <p>ContentProvider简介:android四大组件之一,管理android以结构化方式存放的数据,以相对安全的方式封装数据(表)并提供简易的处理机制和统一的访问接口供其他程序调用.</p> <p>但注意ContentProvider它也只是一个中间人,真正操作的数据源可能是数据库,也可以是文件、xml或网络等其他存储方式。</p> <p>URL(统一资源标识符):代表要操作的数据,可以用来标识每个ContentProvider,这样你就可以通过指定的URI找到想要的ContentProvider,从中获取或修改数据。</p> <p>在Android中URI的格式如下图所示:</p> <p style="text-align:center"><img src="https://simg.open-open.com/show/d9050ff98de6445f8208aacc5b734421.jpg"></p> <p>A <strong>schema,已经由Android所规定为:content://.</strong></p> <p>B 主机名(Authority),是URI的授权部分,是唯一标识符,用来定位ContentProvider。</p> <pre> <code class="language-java">C部分和D部分:是每个ContentProvider内部的路径部分</code></pre> <p>C 指向一个对象集合,一般用表的名字,如果没有指定D部分,则返回全部记录。</p> <p>D 指向特定的记录,这里表示操作user表id为7的记录。如果要操作user表中id为aname7/n法me即可。</p> <p>主要方法</p> <p>public boolean onCreate()</p> <p>ContentProvider创建后 或 打开系统后其它应用第一次访问该CorovidntentPer时调用。</p> <p>public Uri insert(Uri uri, ContentValues values) 外部应用向Contvider中添加数据.</p> <p>public int delete(Uri uri, String selection, String[] selectionArgs) 外部应用从ContentProvider删除数据。</p> <p>public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs):</p> <p>外部应用更新ContentProvider中的数据。</p> <p>public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)</p> <p>供外部应用从ContentProvider中更取数据 .</p> <p>数据库存储方法:</p> <p>代码示例:</p> <pre> <code class="language-java">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; } }</code></pre> <pre> <code class="language-java">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; } }</code></pre> <p>public class NoteDao implements NoteTable {</p> <pre> <code class="language-java">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; } }</code></pre> <pre> <code class="language-java">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) { } }</code></pre> <p>}</p> <p>SharedPreferences的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息,用Sqlite数据库来存放并不划算,因为数据库连接跟操作等耗时大大影响了程序的效率。其存储位置在/data/data/<包名>/shared_prefs目录下。</p> <p>另外SharedPreferences只能保存简单类型的数据,例如,String、int等。一般会将复杂类型的数据转换成Base64编码,然后将转换后的数据以字符串的形式保存在 XML文件中,再用SharedPreferences保存。</p> <p>使用SharedPreferences保存key-value对的步骤如下:</p> <p>(1)使用Activity类的getSharedPreferences方法获得SharedPreferences对象,其中存储key-value的。</p> <p>件的名称由getSharedPreferences方法的第一个参数指定,第二个参数指定访问应用程序私有文件的权限。</p> <p>(2)使用SharedPreferences接口的edit获得SharedPreferences.Editor对象。</p> <p>(3)通过SharedPreferences.Editor接口的putXxx方法保存key-value对。其中Xxx表示不同的数据类型。例如:字符串类型的value需要用putString方法。</p> <p>(4)通过SharedPreferences.Editor接口的commit方法保存key-value对。commit方法相当于数据库事务中的提交(commit)操作。</p> <p> </p> <p>来自:http://blog.csdn.net/google_huchun/article/details/53713265</p> <p> </p>