You may find trouble saving data in your Android app. Wherever you go for saving, you may see the file saved, but after exiting the app, you may lose data. Therefore comes data persistence in Android.
Then, you can store your user data or other stuff somewhere, which data won’t be deleted in the future. Then comes the data persistence methods, including data storing methods either on the device or externally.
This article will teach you what is data persistence in Android and some standard techniques to store data safely.
Kinds of Data Persistence in Android
In general, there you can store data in only two ways. Either you have to save it locally on your mobile device or keep it somewhere else, like on an SD card or cloud storage. So, we can say data persistence in Android is of two types. The first one is, On-device and the Second, Off device.
Besides that, functionality-wise, there are three main categories for data persistence and five categories by sub-categories. So you will see here five categories, and for today we will sort this article into 3 categories.
Five Different Types of Persistent Data in an Android Application
Here we will show you the different persistent data types of all methods available for storing Android application data.
1. Data Storage / File IO
2. Shared preference
3. SQLite Database
4. Custom Content Provider
5. Web Services / Cloud Storage
Let me show you in detail the description.
Data Storage:
Data storage or File IO is more like internal storage for data persistence. In general, This one is easier than others where you can store any data like image, XML, JSON, etc.
Then, as needed, you can keep all the data using this method on your file system. Later you will have an idea of performing this kind of method for your Android device.
Shared Preference:
Shared preference is the kind of data persistence where you can only store XML files to store user data. Like, User id, password, email, or something like that.
Shared Preference can not store media files.
SQLite Database:
SQLite is an embedded type of software where you can write SQL queries to store or manage data. Of course, you can use SQLite or any kind of MDBMS to store data. But, Using SQLite is beneficial because it is lightweight and easy to use on every device.
Custom Content Provider:
This one is related to the SQLite database. You can get data from a database or place data in a database. Therefore, you will see a custom content provider in the SQL database.
Web Services:
You will see this as an off-device where you save files online. This one also refers to a memory card or sd card as a cloud device.
Below you will see these methods sorted according to their similarities, expressed in three ways. Here you will learn those three methods and implementation also.
What is The On-Device Android Data Persistence?
You already know the general categories of data persistence which are broken into five types. Here you will show you another three methods. And you will have an idea of how to do these and how these work.
Java IO Streams
To data persistence first comes local storage or storing data in the phone memory. Then, there come Java IO streams. Using this, you will find a way to customize or do input/output in data storage or shared preference. Here is simple code to do Java IO Streams.
Data Input/Writing File
Open file to input data using java io streams.
FileOutputStream outStream= openFileOutput(“Write the file name”,MODE_WORLD_READABLE);
After choosing the file, write the below code to input data on the file.
String str =”data”; outStream.write(str.getBytes());
outStream.close();
Data Output/Reading File
To fetch data input file name in this logic.
FileInputStream inStream = openFileInput(“Write the file name”);
Now write these method to fetch data from file,
int fileData;
String temporary=””;
while((fileData= inStream.read())!=-1){
temporary = temporary + Character.toString((char)fileData);}
inStream .close();
This is how you can store data using File IO. Also, you can store the shared preferences object in the same category to store login info or other personal data.
Relational Database Management System (RDBMS)
This type of database system can store data using the table. Where columns are used for storing data categories. and rows are for storing single data. There are several types of databases but query-based easy to use one is SQL database. Here you will see the SQLite database. Where you use some simple commands to manipulate data to use. Like, “Select”, “Insert”, “Drop”, “Delete”.
SQLite Database
Before doing any task you will need a table or database created. Therefore we have created a data table below.
package com.example.databasetest;
import Android.content.Context;
import Android.database.sqlite.SQLiteDatabase;
import Android.database.sqlite.SQLiteOpenHelper;
import Android.widget.Toast;
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = “create table book (“
+ “id integer primary key autoincrement, “
+ “author text, “
+ “price real, “
+ “pages integer, “
+ “name text)”;
private Context mContext;
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
Toast.makeText(mContext, “Create succeeded”, Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}}
After Building table lets modify activity_main.xml file:
<LinearLayout xmlns:Android=”http://schemas.Android.com/apk/res/Android”
Android:layout_width=”match_parent”
Android:layout_height=”match_parent”
Android:orientation=”vertical” >
<Button
Android:id=”@+id/create_database”
Android:layout_width=”match_parent”
Android:layout_height=”wrap_content”
Android:text=”Create database”
/>
</LinearLayout>
There is a simple output. you can have a look at the given picture. Only one button appears.
Now you have to change in the MainActivity file to view the output of data input-output on the database.
package com.example.databasetest;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.Button;
public class MainActivity extends AppCompatActivity {
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new MyDatabaseHelper(this, “BookStore.db”, null, 1);
Button createDatabase = (Button) findViewById(R.id.create_database);
createDatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dbHelper.getWritableDatabase();
} }); } }
This is how you can store data in the BookStore database, and now you can store data in this database.
Web Service
Before starting a web service, you have to know some other stuff first. For example, you are storing data in an XML file, Threads, etc. So let us show you from the beginning.
XML Parser
An XML file contains many types of data in itself. Like,
* Prolog (store at first which store data about the file itself)
* Events (There are many events like document start-end or tag start-end.)
* Text (Except tag or document, some files contain texts.)
* Attributes (Generally, values that remain inside a tag are attributes.)
So those will look like,
<?xml version=”1.0″?>
<current>
<city id=”2643743″name=”London”>
<coord lon=”-0.12574″lat=”51.50853″/>
<country>GB</country>
<sun rise=”2013-10-08T06:13:56″set=”2013-10-08T17:21:45″/>
</city>
<temperature value=”289.54″min=”289.15″max=”290.15″unit=”kelvin”/>
<humidity value=”77″unit=”%”/>
<pressure value=”1025″unit=”hPa”/>
</current>
Threads
We can describe threads also as runtime. or execution time for any program.
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run()
{ // compute primes larger than minPrime . . . }
}
This code is to run thread.
PrimeThread p = new PrimeThread(143);
p.start();
Web Service
You may find it difficult to find web service on Android or what web service is? Web service is the same as web on a computer. You can use the browser to find any data, but the Android app can find data online as XML or JSON files. And from there, you may fetch data to present as your wish.
Conclusion
Here we have shown you what is data persistence in android. Hopefully, this article will help you get a brief knowledge about data persistence. Keep following steps to get it to understand fully.
You may also have interested to know:
What is kernel version in Android?
What is Clipboardsaveservice Android?
FAQs
1. What is persistent data in Android?
– Persistent data is stored in Android, which will not be removed or cleared after turning off the application.
2. How many options does Android store persistent data?
– There are 5 options for persistent data in Android.
1. Data Storage / File IO
2. Shared preference
3. SQLite Database
4. Custom Content Provider
5. Web Services / Cloud Storage