Android Universe
Tuesday, 13 October 2015
Wednesday, 17 December 2014
Everything about Android Storage
Android storage is a very important concept when you are building any android application (except when you are building a very simple app).
After reading this post you will be clear on the concept of andriod storage when to use which.
Now, android have various storage options depending on our requirement we can select which option we want to use.
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.
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 a simple example on saving a shared Preference:
Now the data is saved in key-value pair. To fetch this data use the key which you used above.
Below code snippet is an example to read the data from shared preference:
1.Call openFileInput() and pass it the name of the file to read.
2.Read bytes from the file with read().
3.Then close the stream with close().
Example to read data: code snippet
You can check the file created:
First we check if the exteranal storage is available or not by calling:
This returns a String value which represents the state of the external storage
Code Snippet:
From the docs:
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.
Okay, to make it more easy to understand I have made a small application which demonstrate all the above options. Having all the options in one place will be best to understand each and also compare with another.
Click on this github link to access the source code: Database Example
Sqlite database in a different post as this post is getting longer. Cheers!
After reading this post you will be clear on the concept of andriod storage when to use which.
Now, android have various storage options depending on our requirement we can select which option we want to use.
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.
Shared Preference:
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 a simple example on saving a shared Preference:
public class MainActivity extends Activity { private final static String PREFS_NAME = "MySharedPreference"; private final static String SP_KEY_USERNAME = "AppOpened"; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Context.MODE_PRIVATE - available only for your application sp = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);//get a shared preference based on the name (PREFS_NAME) Editor editor = sp.edit(); //get a reference to editor editor.putString(SP_KEY_USERNAME, "ik"); //insert the value editor.commit(); //commit the changes } }
Now the data is saved in key-value pair. To fetch this data use the key which you used above.
Below code snippet is an example to read the data from shared preference:
//first check if the key already exists in shared preference if(sp.contains(SP_KEY_USERNAME)){//if yes String username = sp.getString(SP_KEY_USERNAME, "Default value"); //get the value }
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.
2.Write to the file with write().
3.Close the stream with close().
Example to write data: Code Snippet
To create and write a private file to the internal storage:
1.Call openFileOutput() with the name of the file and the operating mode.
2.Write to the file with write().
3.Close the stream with close().
Example to write data: Code Snippet
FileOutputStre fos = null; String helloWorld = "Hello, World!"; try { fos = openFileOutput(TEXT_FILE_NAME, Context.MODE_PRIVATE); //MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. fos.write(helloWorld.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); //make sure you call close. } catch (IOException e) { e.printStackTrace(); } } } //MODE_APPEND - File creation mode: for use with openFileOutput(String, int), if the file already exists then write data to the end of the existing file instead of erasing it.To read a file from internal storage:
1.Call openFileInput() and pass it the name of the file to read.
2.Read bytes from the file with read().
3.Then close the stream with close().
Example to read data: code snippet
FileInputStream fis = null; //reading the data try { fis = openFileInput(TEXT_FILE_NAME); StringBuffer buffer = new StringBuffer();//normal string will not allows us to modify its data so use StringBuffer int byteRead = -1; //-1 => end of file while((byteRead = fis.read()) != -1){ buffer.append((char)byteRead); } Log.d("Data: ", buffer.toString()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(this, "Read Sccessfully - Check Log cat ", 0).show(); }
You can check the file created:
- Goto the DDMS mode in your IDE
- Go inside data/data
- Followed by your package name
- Then select files. You should see the file which you just created in there
External Storage:
External storage is different from internal storage when it comes to accessing beacause external storage may or may not be present in users device. We dont want our app to read/wite data to external storage if it is not present. So for that we need to check the state of external storage before we try to access it.First we check if the exteranal storage is available or not by calling:
Environment.getExternalStorageState();
This returns a String value which represents the state of the external storage
Code Snippet:
String state = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)){ //we can read and write to external storage } else if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){ //we can only read external storage }
From the docs:
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.
Saving cache files
If you'd like to cache some data, rather than store it persistently, you should usegetCacheDir()to open a File that 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.
//To Store File cacheDir = getCacheDir(); //return the path where the cache files are going to be saved File file = new File(chachedir.getAbsolutePath(),"mytext.txt"); FileOutputStream fos = new FileOutputStream(file); //To Read File cacheDir = getCacheDir(); File file = new File(cacheDir, "mytext.txt"); FileInputStream fin = new FileInputStream(file);
Okay, to make it more easy to understand I have made a small application which demonstrate all the above options. Having all the options in one place will be best to understand each and also compare with another.
Click on this github link to access the source code: Database Example
Sqlite database in a different post as this post is getting longer. Cheers!
Monday, 15 December 2014
Supporting Material Design features in lower versions of Android
Importing Appcompat v-21 library in your project
First things first we need to import appcompat v-21 library into our project. To do this make sure your sdk is up to date (you can do this by going to the sdk manager).
If incase you run into some problem then google it out, you will find solutions to every problem :)
Now once you have your sdk updated you need to import it into your project.
To do this:
- First import the appcompat in your work space.
- Then right click on your project ->select Properties-> select Android-> Click on Add and select appcompat which you just imported in your work space.
- Right click on your project ->select Properties-> select Android-> Select Android 5.0 as your Target Name.
Subscribe to:
Posts (Atom)