Why store information ?
As developers we have to take care of our user preferences
of our app. This includes various services such as storing user preferred
settings. We can store our application data in files, databases or preferences
in internal or removable storage such as memory card. You can also add a data
backup service to let users store and recover application and system data.
Storing user application data is a way of “EFFICIENT PROGRAMMING“ as it reduces the burden for the user to enter
the details every time he uses the
application.
Since we now know the importance of storage in our
application, we learn what are the different ways of storing user data of our
application.
Android provides several options to store application data.
The method we choose completely depends on certain needs such as space required
to store the data and restrictions such as whether the data is to be made
available to all the users and other applications.
The available options of storage are :
1 . Shared Preferences
2. Internal storage
3. external storage
4. Android’s SQLite databases and
5. Network conncetion
1.
Shared Preferences:
The Shared Preferences class provides a general framework that lets
your app store information which are primitive data types. The data is mainly
stored as key-value pairs. The primitive datatypes include Boolean, int , float
and so on.
We have two methods of Shared Preferences
class :
1.
getSharedPreferences()
2.
getPreferences()
The first method getSharedPreferences is used when you want
to store multiple preference files by which are further referenced by names. If
you need just one preference file then you use getPreferences().
Let us see a simple example android app which demonstrates
Shared Preferences:
Activity_main.xml
<?xml
version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.raman.myapplication.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Preferences" />
<CheckBox
android:text="preference 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="39dp"
android:layout_marginStart="39dp"
android:layout_marginTop="24dp"
android:id="@+id/checkBox" />
<CheckBox
android:text="preference 2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/checkBox"
android:layout_alignRight="@+id/checkBox"
android:layout_alignEnd="@+id/checkBox"
android:layout_marginTop="22dp"
android:id="@+id/checkBox2" />
</RelativeLayout>

MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String pref_file="My pref file";
CheckBox c1,c2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c1=(CheckBox)findViewById(R.id.checkBox);
c2=(CheckBox)findViewById(R.id.checkBox2);
SharedPreferences preferences=getSharedPreferences(pref_file,0);
boolean check1=preferences.getBoolean("pref1",false);
boolean check2=preferences.getBoolean("pref2",false);
c1.setChecked(check1);
c2.setChecked(check2);
}
public void onStop(){
super.onStop();
SharedPreferences settings=getSharedPreferences(pref_file,0);
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("pref1",c1.isChecked());
editor.putBoolean("pref2",c2.isChecked());
editor.commit();
}
}
2 Using internal storage :
So far we have seen how to store application data in the form of Shared
Preferences which are key value pairs.
Now let us learn how to store files in the internal storage of our
phone.
Inorder to perform the above task we use openFileOutput() which returns
a FileOutputStream object.
Using that object and write() , we write to the file.
Finally we close the output stream.
1. Call openFileOutput() with the name of the file and the operating
permissions
2. Write to the file using write()
3. Close the stream with close();
Reading the saved file:
· Call the openFileInput() passing the
file name as parameter.
· Next step is to call the read().
· Next close the input stream.
Now let us build a simple example application to demonstrate file
storage using internal memory.
Activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.raman.internal.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="@+id/edit"
android:hint="enter your text"
android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/submit"
android:layout_alignStart="@+id/submit" />
<Button
android:text="save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="45dp"
android:layout_marginStart="45dp"
android:layout_marginTop="49dp"
android:id="@+id/submit"
android:layout_below="@+id/edit"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="get file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/submit"
android:layout_alignRight="@+id/edit"
android:layout_alignEnd="@+id/edit"
android:id="@+id/get" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/submit"
android:layout_toRightOf="@+id/submit"
android:layout_toEndOf="@+id/submit"
android:layout_marginTop="136dp"
android:id="@+id/show" />
</RelativeLayout>

MainActivity.java file
public
class MainActivity extends
AppCompatActivity {
String file="sample";
String string="Welcome to efficient programmer.com";
EditText text;
Button submit,get;
String res="";
TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(EditText)findViewById(R.id.edit);
show=(TextView)findViewById(R.id.show);
submit=(Button)findViewById(R.id.submit);
get=(Button)findViewById(R.id.get);
// writing data to a file
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
FileOutputStream
fileOutputStream = openFileOutput(file, Context.MODE_PRIVATE);
string = text.getText().toString();
fileOutputStream.write(string.getBytes());
fileOutputStream.close();
Toast.makeText(getApplicationContext(),"FILE SAVED",Toast.LENGTH_LONG).show();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try{
String line;
FileInputStream
fis=openFileInput(file);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
while ((line=br.readLine())!=null)
res=res+line;
show.setText(res);
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
}

Now on clicking the save button, the file is saved to the internal
memory. When we click on the get file button, the information is retrieved from
the file and shown on the textView.
Comments
Post a Comment
Thanks for your comments!