保存数据篇:
andriod提供了三种保存数据的方式
1.通过Key-Value Sets来存储数据
通过SharedPreferences APIs中提供的的方法来进行保存,
示例代码:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
写入SharedPreferences为:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();editor.putInt(getString(R.string.saved_high_score), newHighScore);editor.commit();
读取SharedPreferences的代码为:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
2.通过Files来 存储数据
通过文件来保存数据,分为内部存储文件和外部存储文件,
内部存储:
内部存储总是可用的,
系统默认的安装和卸载app都是在内部存储进行的,
内部存储是不能访问的,在没有root的前提下,
内部存储文件时不需要在AndroidManifest清单文件中注册
你的APP可以调用两个方法getFilesDir()和getCacheDir(),
示例代码:
File file = new File(context.getFilesDir(), filename); //这是搞出一个file的代码
将文件写入内部存储卡的实例代码:
String filename = "myfile";
String string = "Hello world!";FileOutputStream outputStream;
try {outputStream = openFileOutput(filename, Context.MODE_PRIVATE);outputStream.write(string.getBytes());outputStream.close();} catch (Exception e) {e.printStackTrace();}
如果你的文件想要缓存的话,可以参考下面的代码:
public File getTempFile(Context context, String url) {
File file;try {String fileName = Uri.parse(url).getLastPathSegment();file = File.createTempFile(fileName, null, context.getCacheDir());catch (IOException e) {// Error while creating file}return file;}
外部存储:
1.外部存储和扩展存储卡可以看成一体2.外部存储并不总是可用的,当用户将扩展存储卡移除或者连接USB的时候,外部存储都是不可用的状态3.外部存储适合放置一些共享性文件,比如音乐,视频,应用离线数据包或者一些游戏的数据包。
想在外部储存进行读写数据,必须在AndroidManifest清单文件中注册
具体代码
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />...</manifest>
同内部存储的不同,因为外部存储可能不可用,所以要先进行检测,看外部存储是否可用,具体方法为:getExternalStorageState();
实例代码:
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {String state = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(state)) {return true;}return false;}
/* Checks if external storage is available to at least read */public boolean isExternalStorageReadable() {String state = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(state) ||Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {return true;}return false;}
外部存储存储的文件也有两种,一种是public,一种是private
可以调用两个不同的方法,getExternalStoragePublicDirectory(), getExternalFilesDir(),
示例代码:
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName);if (!file.mkdirs()) {Log.e(LOG_TAG, "Directory not created");}return file;}
public File getAlbumStorageDir(Context context, String albumName) {// Get the directory for the app's private pictures directory.File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), albumName);if (!file.mkdirs()) {Log.e(LOG_TAG, "Directory not created");}return file;}
查看外部存储的剩余空间可以调用两个方法进行查看
getFreeSpace() 和 getTotalSpace();
得到剩余存储空间 得到总存储空间
删除数据
delete()方法,如果文件在内部存储上,也可以调用deleteFile();
注意一点:
卸载app时,内部存储上的所有文件都会被删除,外部存储上的文件使用getExternalFilesDir()方法保存的能被删除。
同时也要把缓存文件和不需要的文件也删除掉。
3.通过数据库(SQLLite)来存储数据
Android才用SQLLite数据库进行保存数据,这里不对SQLLite进行阐述,使用数据库的介绍会有新的篇章。
这里是典型的关系型数据库,其实就是进行CRUD的操作。
直接上示例代码:
1、增加数据
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keysContentValues values = new ContentValues();values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID, id);values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT, content);
// Insert the new row, returning the primary key value of the new rowlong newRowId;newRowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME,FeedReaderContract.FeedEntry.COLUMN_NAME_NULLABLE,values);2、查看数据SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database// you will actually use after this query.String[] projection = {FeedReaderContract.FeedEntry._ID,FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE,FeedReaderContract.FeedEntry.COLUMN_NAME_UPDATED,...};
// How you want the results sorted in the resulting CursorString sortOrder =FeedReaderContract.FeedEntry.COLUMN_NAME_UPDATED + " DESC";
Cursor c = db.query(FeedReaderContract.FeedEntry.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
3、修改数据:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
ContentValues values = new ContentValues();values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";String[] selectionArgs = { String.valueOf(rowId) };
int count = db.update(FeedReaderDbHelper.FeedEntry.TABLE_NAME,values,selection,selectionArgs);4、删除数据:SQLiteDatabase db = mDbHelper.getReadableDatabase();String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
db.delete(table_name, selection, selectionArgs);