Android存儲數據方式

可以查看Android開發文檔中的:/docs/guide/topics/data/data-storage.html

Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs,

such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires.

Your data storage options are the following:

Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.

Android provides a way for you to expose even your private data to other applications — with a?content provider. A content provider is an optional component that exposes read/write access to your application data, subject to whatever restrictions you want to impose. For more information about using content providers, see the?Content Providers?documentation.

?

Using Shared Preferences

The?SharedPreferences?class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.

You can use?SharedPreferences?to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

To get a?SharedPreferences?object for your application, use one of two methods:

  • getSharedPreferences()?- Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
  • getPreferences()?- Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

To write values:

  1. Call?edit()?to get a?SharedPreferences.Editor.
  2. Add values with methods such as?putBoolean()?and?putString().
  3. Commit the new values with?commit()

To read values, use?SharedPreferences?methods such as?getBoolean()?and?getString().

Here is an example that saves a preference for silent keypress mode in a calculator:

public class Calc extends Activity {public static final String PREFS_NAME = "MyPrefsFile";@Overrideprotected void onCreate(Bundle state){super.onCreate(state);. . .// Restore preferencesSharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);boolean silent = settings.getBoolean("silentMode", false);setSilent(silent);}@Overrideprotected void onStop(){super.onStop();// We need an Editor object to make preference changes.// All objects are from android.context.ContextSharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);SharedPreferences.Editor editor = settings.edit();editor.putBoolean("silentMode", mSilentMode);// Commit the edits!
      editor.commit();}
}

Using the Internal Storage

You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.

To create and write a private file to the internal storage:

  1. Call?openFileOutput()?with the name of the file and the operating mode. This returns a?FileOutputStream.
  2. Write to the file with?write().
  3. Close the stream with?close().

For example:

String FILENAME = "hello_file";
String string = "hello world!";FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

MODE_PRIVATE?will create the file (or replace a file of the same name) and make it private to your application. Other modes available are:?MODE_APPEND,?MODE_WORLD_READABLE, and?MODE_WORLD_WRITEABLE.

To read a file from internal storage:

  1. Call?openFileInput()?and pass it the name of the file to read. This returns a?FileInputStream.
  2. Read bytes from the file with?read().
  3. Then close the stream with?close().

Tip:?If you want to save a static file in your application at compile time, save the file in your project?res/raw/directory. You can open it with?openRawResource(), passing the?R.raw.<filename>?resource ID. This method returns an?InputStream?that you can use to read the file (but you cannot write to the original file).

Saving cache files

If you'd like to cache some data, rather than store it persistently, you should use?getCacheDir()?to open a?Filethat represents the internal directory where your application should save temporary cache files.

When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.

Other useful methods

getFilesDir()
Gets the absolute path to the filesystem directory where your internal files are saved.
getDir()
Creates (or opens an existing) directory within your internal storage space.
deleteFile()
Deletes a file saved on the internal storage.
fileList()
Returns an array of files currently saved by your application.

Using the External Storage

Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.

Caution:?External storage can become unavailable if the user mounts the external storage on a computer or removes the media, and there's no security enforced upon files you save to the external storage. All applications can read and write files placed on the external storage and the user can remove them.

Getting access to external storage

In order to read or write files on the external storage, your app must acquire the?READ_EXTERNAL_STORAGE?orWRITE_EXTERNAL_STORAGE?system permissions. For example:

<manifest ...><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />...
</manifest>

If you need to both read and write files, then you need to request only the?WRITE_EXTERNAL_STORAGE?permission, because it implicitly requires read access as well.

Note:?Beginning with Android 4.4, these permissions are not required if you're reading or writing only files that are private to your app. For more information, see the section below about?saving files that are app-private.

Checking media availability

Before you do any work with the external storage, you should always call?getExternalStorageState()?to check whether the media is available. The media might be mounted to a computer, missing, read-only, or in some other state. For example, here are a couple methods you can use to check the availability:

/* 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;
}

The?getExternalStorageState()?method returns other states that you might want to check, such as whether the media is being shared (connected to a computer), is missing entirely, has been removed badly, etc. You can use these to notify the user with more information when your application needs to access the media.

Saving files that can be shared with other apps

Generally, new files that the user may acquire through your app should be saved to a "public" location on the device where other apps can access them and the user can easily copy them from the device. When doing so, you should use to one of the shared public directories, such as?Music/,?Pictures/, and?Ringtones/.

To get a?File?representing the appropriate public directory, callgetExternalStoragePublicDirectory(), passing it the type of directory you want, such as?DIRECTORY_MUSIC,DIRECTORY_PICTURES,?DIRECTORY_RINGTONES, or others. By saving your files to the corresponding media-type directory, the system's media scanner can properly categorize your files in the system (for instance, ringtones appear in system settings as ringtones, not as music).

For example, here's a method that creates a directory for a new photo album in the public pictures directory:

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;
}

Saving files that are app-private

If you are handling files that are not intended for other apps to use (such as graphic textures or sound effects used by only your app), you should use a private storage directory on the external storage by callinggetExternalFilesDir(). This method also takes a?type?argument to specify the type of subdirectory (such asDIRECTORY_MOVIES). If you don't need a specific media directory, pass?null?to receive the root directory of your app's private directory.

Beginning with Android 4.4, reading or writing files in your app's private directories does not require theREAD_EXTERNAL_STORAGE?or?WRITE_EXTERNAL_STORAGE?permissions. So you can declare the permission should be requested only on the lower versions of Android by adding the?maxSdkVersion?attribute:

<manifest ...><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"android:maxSdkVersion="18" />...
</manifest>

Note:?When the user uninstalls your application, this directory and all its contents are deleted. Also, the system media scanner does not read files in these directories, so they are not accessible from theMediaStore?content provider. As such, you?should not use these directories?for media that ultimately belongs to the user, such as photos captured or edited with your app, or music the user has purchased with your app—those files should be?saved in the public directories.

Sometimes, a device that has allocated a partition of the internal memory for use as the external storage may also offer an SD card slot. When such a device is running Android 4.3 and lower, the?getExternalFilesDir()method provides access to only the internal partition and your app cannot read or write to the SD card. Beginning with Android 4.4, however, you can access both locations by calling?getExternalFilesDirs(), which returns aFile?array with entries each location. The first entry in the array is considered the primary external storage and you should use that location unless it's full or unavailable. If you'd like to access both possible locations while also supporting Android 4.3 and lower, use the?support library's?static method,ContextCompat.getExternalFilesDirs(). This also returns a?File?array, but always includes only one entry on Android 4.3 and lower.

Caution?Although the directories provided by?getExternalFilesDir()?and?getExternalFilesDirs()?are not accessible by the?MediaStore?content provider, other apps with the?READ_EXTERNAL_STORAGEpermission can access all files on the external storage, including these. If you need to completely restrict access for your files, you should instead write your files to the?internal storage.

Saving cache files

To open a?File?that represents the external storage directory where you should save cache files, callgetExternalCacheDir(). If the user uninstalls your application, these files will be automatically deleted.

Similar to?ContextCompat.getExternalFilesDirs(), mentioned above, you can also access a cache directory on a secondary external storage (if available) by calling?ContextCompat.getExternalCacheDirs().

Tip:?To preserve file space and maintain your app's performance, it's important that you carefully manage your cache files and remove those that aren't needed anymore throughout your app's lifecycle.

Using Databases

Android provides full support for?SQLite?databases. Any databases you create will be accessible by name to any class in the application, but not outside the application.

The recommended method to create a new SQLite database is to create a subclass of?SQLiteOpenHelper?and override the?onCreate()?method, in which you can execute a SQLite command to create tables in the database. For example:

public class DictionaryOpenHelper extends SQLiteOpenHelper {private static final int DATABASE_VERSION = 2;private static final String DICTIONARY_TABLE_NAME = "dictionary";private static final String DICTIONARY_TABLE_CREATE ="CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +KEY_WORD + " TEXT, " +KEY_DEFINITION + " TEXT);";DictionaryOpenHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(DICTIONARY_TABLE_CREATE);}
}

You can then get an instance of your?SQLiteOpenHelper?implementation using the constructor you've defined. To write to and read from the database, call?getWritableDatabase()?and?getReadableDatabase(), respectively. These both return a?SQLiteDatabase?object that represents the database and provides methods for SQLite operations.

You can execute SQLite queries using the?SQLiteDatabasequery()?methods, which accept various query parameters, such as the table to query, the projection, selection, columns, grouping, and others. For complex queries, such as those that require column aliases, you should use?SQLiteQueryBuilder, which provides several convienent methods for building queries.

Every SQLite query will return a?Cursor?that points to all the rows found by the query. The?Cursor?is always the mechanism with which you can navigate results from a database query and read rows and columns.

For sample apps that demonstrate how to use SQLite databases in Android, see the?Note Pad?and?Searchable Dictionary?applications.

Database debugging

The Android SDK includes a?sqlite3?database tool that allows you to browse table contents, run SQL commands, and perform other useful functions on SQLite databases. See?Examining sqlite3 databases from a remote shell?to learn how to run this tool.

Using a Network Connection

You can use the network (when it's available) to store and retrieve data on your own web-based services. To do network operations, use classes in the following packages:

  • java.net.*
  • android.net.*

轉載于:https://www.cnblogs.com/liaojie970/p/5829909.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/254547.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/254547.shtml
英文地址,請注明出處:http://en.pswp.cn/news/254547.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

防止cpu 一直被占用 sleep(0) 和 yield

在java的Thread類中有兩個有用的函數&#xff0c;sleep和yield&#xff0c;sleep就是線程睡眠一定的時間&#xff0c;也就是交出cpu一段時間&#xff0c;yield用來暗示系統交出cpu控制權。這兩個函數在多線程開發的時候特別有用&#xff0c;可以合理的分配cpu&#xff0c;提高程…

做一個有膽識的有為青年

1、一個年輕人&#xff0c;如果在這四年的時間里&#xff0c;沒有任何想法&#xff0c;他這一生&#xff0c;就基本這個樣子&#xff0c;沒有多大改變了。 2、成功者就是膽識加魄力&#xff0c;曾經在火車上聽人談起過溫州人的成功&#xff0c;說了這么三個字&#xff0c;“膽…

jstack應用-查找CPU飚高的原因

場景 在系統上線后&#xff0c;經常會遇到運維的同學跑過來說&#xff1a;“這次發版后&#xff0c;cpu線程使用率到一場&#xff0c;到100%了”。這時候不要慌&#xff0c;可以使用堆轉儲來分析到底是哪個線程引起的。 查找元兇 [rootjava_mofei_01 test]# top Mem: 16333644…

Enhancement增強圖形halcon算子,持續更新

目錄coherence_enhancing_diffemphasizeequ_histo_imageilluminatemean_curvature_flowscale_image_max_shock_filtercoherence_enhancing_diff 功能&#xff1a;執行一個圖像的一個一致性增強擴散。 emphasize 功能&#xff1a;增強圖像對比度。 equ_histo_image 功能&am…

音頻中采樣位數,采樣率,比特率的名詞解釋(轉)

采樣位數&#xff08;采樣大小&#xff09;&#xff1a; 采樣位數可以理解為采集卡處理聲音的解析度。這個數值越大&#xff0c;解析度就越高&#xff0c;錄制和回放的聲音就越真實。我們首先要知道&#xff1a;電腦中的聲音文件是用數字0和1來表示的。所以在電腦上錄音的本質就…

WebSocket實時異步通信

WebSocket實時異步通信 【一】WebSocket簡介 WebSocket是HTML5推出一個協議規范&#xff0c;用來B/S模式中服務器端和客戶端之間進行實時異步通信。 眾所周知&#xff0c;傳統的HTTP協議中&#xff0c;服務器端和客戶端通信只能是在客戶端發送一個請求之后&#xff0c;服務器端…

多線程和多進程的區別(小結)

分類&#xff1a; linux 2009-06-19 09:33 11501人閱讀 評論(15) 收藏 舉報 很想寫點關于多進程和多線程的東西&#xff0c;我確實很愛他們。但是每每想動手寫點關于他們的東西&#xff0c;卻總是求全心理作祟&#xff0c;始終動不了手。 今天終于下了決心&#xff0c;寫點東西…

redis-cli使用密碼登錄

redis-cli使用密碼登錄 注意IP地址要寫正確&#xff01; 學習了: https://blog.csdn.net/lsm135/article/details/52932896 https://blog.csdn.net/zyz511919766/article/details/42268219 https://zhidao.baidu.com/question/756651357338691604.html 登錄后 auth pass 或者 r…

FFT快速傅式變換算法halcon算子,持續更新

目錄convol_fftconvol_gaborcorrelation_fftdeserialize_fft_optimization_dataenergy_gaborfft_genericfft_imagefft_image_invgen_bandfiltergen_bandpassgen_derivative_filtergen_filter_maskgen_gaborgen_gauss_filtergen_highpassgen_lowpassgen_mean_filtergen_sin_band…

仿照vue實現簡易的MVVM框架(一)

代碼github地址&#xff1a; https://github.com/susantong/myMVVM 主要的方法有&#xff1a; compile 深度遍歷前端界面的節點&#xff0c;將其復制進一個addQuene隊列中pasers 遍歷所有的節點&#xff0c;并將節點包裝成一個含有本節點、自定義屬性及屬性值的對象。要想實現雙…

tomcat 啟動時內存溢出

在tomcat_home/bin目錄下找到catalina.bat&#xff0c;用文本編輯器打開&#xff0c;加上下面一行&#xff1a; set JAVA_OPTS -Xms1024M -Xmx1024M -XX:PermSize256M -XX:MaxNewSize256M -XX:MaxPermSize256M 解釋一下各個參數&#xff1a; -Xms1024M&#xff1a;初始化堆內存…

@angular/platform-browser-dynamic

/** experimental */ export declare class JitCompilerFactory implements CompilerFactory {createCompiler(options?: CompilerOptions[]): Compiler; }export declare const platformBrowserDynamic: (extraProviders?: StaticProvider[] | undefined) > PlatformRef;…

牛人項目失敗的總結

tom_lt: 遇到的失敗項目比較多&#xff01;讓人郁悶&#xff01;&#xff01; 仔細分析原因&#xff0c;主要在于&#xff1a; 1.項目開始需求不明確。領導決定動手&#xff0c;就開始啟動項目&#xff0c;造成和客戶需要差距太大&#xff0c;導致失敗&#xff1b; 2.需求變更沒…

Android:日常學習筆記(8)———探究UI開發(5)

Android:日常學習筆記(8)———探究UI開發(5) ListView控件的使用 ListView概述 A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view. 1.關于ArrayAdapter&#xff1a; ArrayAdapter<T> 是 ListAd…

Geometric-Transformations圖像幾何變換halcon算子,持續更新

目錄affine_trans_imageaffine_trans_image_sizeconvert_map_typemap_imagemirror_imagepolar_trans_image_extpolar_trans_image_invprojective_trans_imageprojective_trans_image_sizerotate_imagezoom_image_factorzoom_image_sizeaffine_trans_image 功能&#xff1a;把任…

hibernate inverse屬性的作用

hibernate配置文件中有這么一個屬性inverse&#xff0c;它是用來指定關聯的控制方的。inverse屬性默認是false&#xff0c;若為false&#xff0c;則關聯由自己控制&#xff0c;若為true&#xff0c;則關聯由對方控制。見例子&#xff1a; 一個Parent有多個Child,一個Child只能有…

分布式鎖與實現(一)——基于Redis實現

概述 目前幾乎很多大型網站及應用都是分布式部署的&#xff0c;分布式場景中的數據一致性問題一直是一個比較重要的話題。分布式的CAP理論告訴我們“任何一個分布式系統都無法同時滿足一致性&#xff08;Consistency&#xff09;、可用性&#xff08;Availability&#xff09;和…

淺析軟件項目管理中十個誤區(來自:http://manager.csdn.net/n/20051213/30907.html)

隨著計算機硬件水平的不斷提高&#xff0c;計算機軟件的規模和復雜度也隨之增加。計算機軟件開發從“個人英雄”時代向團隊時代邁進&#xff0c;計算機軟件項目的管理也從“作坊式”管理向“軟件工廠式”管理邁進。這就要求軟件開發人員特別是軟件項目管理人員更深一步地理解和…

倆孩隨筆

倆孩隨筆 有人給我貼了技術男加奶爸的標簽&#xff0c;不過這兩項都不是我的強項。我深知自己最大的長處在哪&#xff1a;普通&#xff0c;扔人堆里&#xff0c;不是認不出來&#xff0c;而是壓根看不著。想把事情做好&#xff0c;常常會用力過度。工作平平淡淡&#xff0c;需…

Inpainting圖像修復halcon算子,持續更新

目錄harmonic_interpolationinpainting_anisoinpainting_cedinpainting_ctinpainting_mcfinpainting_textureharmonic_interpolation 功能&#xff1a;對一個圖像區域執行諧波插值。 inpainting_aniso 功能&#xff1a;通過各向異性擴散執行圖像修復。 inpainting_ced 功能…