Android Preferences Example
Android shared preference is used to store and retrieve primitive information. In android, string, integer, long, number etc. are considered as primitive data type.
Android Shared preferences are used to store data in key and value pair so that we can retrieve the value on the basis of key.
It is widely used to get information from user such as in settings.
Android Preferences Example
Let's see a simple example of android shared preference.
activity_main.xml
Drag one textview and two buttons from the pallete.
File: activity_main.xml
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity" >
- <TextView
- android:id="@+id/txtPrefs"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerVertical="true"
- android:text="Data:" />
- <Button
- android:id="@+id/storeinformation"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/showinformation"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="18dp"
- android:text="Store Information" />
- <Button
- android:id="@+id/showinformation"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="17dp"
- android:text="Show Information" />
- </RelativeLayout>
array.xml
It is created inside res/values directory.
File: array.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string-array name="listOptions">
- <item>English</item>
- <item>Hindi</item>
- <item>Other</item>
- </string-array>
- <string-array name="listValues">
- <item>English Language</item>
- <item>Hindi Language</item>
- <item>Other Language</item>
- </string-array>
- </resources>
prefs.xml
It is created inside res/xml directory.
File: prefs.xml
- <?xml version="1.0" encoding="utf-8"?>
- <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
- <PreferenceCategory
- android:summary="Username and password information"
- android:title="Login information" >
- <EditTextPreference
- android:key="username"
- android:summary="Please enter your login username"
- android:title="Username" />
- <EditTextPreference
- android:key="password"
- android:summary="Enter your password"
- android:title="Password" />
- </PreferenceCategory>
- <PreferenceCategory
- android:summary="Username and password information"
- android:title="Settings" >
- <CheckBoxPreference
- android:key="checkBox"
- android:summary="On/Off"
- android:title="Keep me logged in" />
- <ListPreference
- android:entries="@array/listOptions"
- android:entryValues="@array/listValues"
- android:key="listpref"
- android:summary="List preference example"
- android:title="List preference" />
- </PreferenceCategory>
- </PreferenceScreen>
Preference Demo Activity Class
File: PreferenceDemoActivity.java
- package com.example.preferences;
- import android.os.Bundle;
- import android.preference.PreferenceManager;
- import android.app.Activity;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.view.Menu;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- public class PreferenceDemoActivity extends Activity {
- TextView textView;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Button storeinformation = (Button) findViewById(R.id.storeinformation);
- Button showinformation = (Button) findViewById(R.id.showinformation);
- textView = (TextView) findViewById(R.id.txtPrefs);
- View.OnClickListener listener = new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.storeinformation:
- Intent intent = new Intent(PreferenceDemoActivity.this,PrefsActivity.class);
- startActivity(intent);
- break;
- case R.id.showinformation:
- displaySharedPreferences();
- break;
- default:
- break;
- }
- }
- };
- storeinformation.setOnClickListener(listener);
- showinformation.setOnClickListener(listener);
- }
- private void displaySharedPreferences() {
- SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PreferenceDemoActivity.this);
- String username = prefs.getString("username", "Default NickName");
- String passw = prefs.getString("password", "Default Password");
- boolean checkBox = prefs.getBoolean("checkBox", false);
- String listPrefs = prefs.getString("listpref", "Default list prefs");
- StringBuilder builder = new StringBuilder();
- builder.append("Username: " + username + "\n");
- builder.append("Password: " + passw + "\n");
- builder.append("Keep me logged in: " + String.valueOf(checkBox) + "\n");
- builder.append("List preference: " + listPrefs);
- textView.setText(builder.toString());
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- }
PrefsActivity class
File: PrefsActivity.java
- package com.example.preferences;
- import android.os.Bundle;
- import android.preference.PreferenceActivity;
- public class PrefsActivity extends PreferenceActivity{
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- addPreferencesFromResource(R.xml.prefs);
- }
- }
Output:
Click on the store information button.
Now click on username and store information. Like username, store password and click on the checkbox.
Now click on the list preference to store language information.
Now click on the back button to come to first activity. Now click on the show information button.
Android Internal Storage Example
We are able to save or read data from the device internal memory. FileInputStream and FileOutputStream classes are used to read and write data into the file.
Here, we are going to read and write data to the internal storage of the device.
Example of reading and writing data to the android internal storage
activity_main.xml
Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity" >
- <EditText
- android:id="@+id/editText1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_alignParentTop="true"
- android:layout_marginRight="20dp"
- android:layout_marginTop="24dp"
- android:ems="10" >
- <requestFocus />
- </EditText>
- <EditText
- android:id="@+id/editText2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignRight="@+id/editText1"
- android:layout_below="@+id/editText1"
- android:layout_marginTop="24dp"
- android:ems="10" />
- <TextView
- android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/editText1"
- android:layout_alignBottom="@+id/editText1"
- android:layout_alignParentLeft="true"
- android:text="File Name:" />
- <TextView
- android:id="@+id/textView2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/editText2"
- android:layout_alignBottom="@+id/editText2"
- android:layout_alignParentLeft="true"
- android:text="Data:" />
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/editText2"
- android:layout_below="@+id/editText2"
- android:layout_marginLeft="70dp"
- android:layout_marginTop="16dp"
- android:text="save" />
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/button1"
- android:layout_alignBottom="@+id/button1"
- android:layout_toRightOf="@+id/button1"
- android:text="read" />
- </RelativeLayout>
Activity class
Let's write the code to write and read data from the internal storage.
File: MainActivity.java
- package com.example.internalstorage;
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.Context;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- EditText editTextFileName,editTextData;
- Button saveButton,readButton;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- editTextFileName=(EditText)findViewById(R.id.editText1);
- editTextData=(EditText)findViewById(R.id.editText2);
- saveButton=(Button)findViewById(R.id.button1);
- readButton=(Button)findViewById(R.id.button2);
- //Performing Action on Read Button
- saveButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View arg0) {
- String filename=editTextFileName.getText().toString();
- String data=editTextData.getText().toString();
- FileOutputStream fos;
- try {
- fos = openFileOutput(filename, Context.MODE_PRIVATE);
- //default mode is PRIVATE, can be APPEND etc.
- fos.write(data.getBytes());
- fos.close();
- Toast.makeText(getApplicationContext(),filename + " saved",
- Toast.LENGTH_LONG).show();
- } catch (FileNotFoundException e) {e.printStackTrace();}
- catch (IOException e) {e.printStackTrace();}
- }
- });
- //Performing Action on Read Button
- readButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View arg0) {
- String filename=editTextFileName.getText().toString();
- StringBuffer stringBuffer = new StringBuffer();
- try {
- //Attaching BufferedReader to the FileInputStream by the help of InputStreamReader
- BufferedReader inputReader = new BufferedReader(new InputStreamReader(
- openFileInput(filename)));
- String inputString;
- //Reading data line by line and storing it into the stringbuffer
- while ((inputString = inputReader.readLine()) != null) {
- stringBuffer.append(inputString + "\n");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- //Displaying data on the toast
- Toast.makeText(getApplicationContext(),stringBuffer.toString(),
- Toast.LENGTH_LONG).show();
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- }
Android External Storage Example
Like internal storage, we are able to save or read data from the device external memory such as sdcard. FileInputStream and FileOutputStream classes are used to read and write data into the file.
Example of reading and writing data in the android external storage
activity_main.xml
Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity" >
- <EditText
- android:id="@+id/editText1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_alignParentTop="true"
- android:layout_marginRight="20dp"
- android:layout_marginTop="24dp"
- android:ems="10" >
- <requestFocus />
- </EditText>
- <EditText
- android:id="@+id/editText2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignRight="@+id/editText1"
- android:layout_below="@+id/editText1"
- android:layout_marginTop="24dp"
- android:ems="10" />
- <TextView
- android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/editText1"
- android:layout_alignBottom="@+id/editText1"
- android:layout_alignParentLeft="true"
- android:text="File Name:" />
- <TextView
- android:id="@+id/textView2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/editText2"
- android:layout_alignBottom="@+id/editText2"
- android:layout_alignParentLeft="true"
- android:text="Data:" />
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/editText2"
- android:layout_below="@+id/editText2"
- android:layout_marginLeft="70dp"
- android:layout_marginTop="16dp"
- android:text="save" />
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/button1"
- android:layout_alignBottom="@+id/button1"
- android:layout_toRightOf="@+id/button1"
- android:text="read" />
- </RelativeLayout>
Provide permission for the external storage
You need to provide the WRITE_EXTERNAL_STORAGE permission.
File: Activity_Manifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest
- xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.externalstorage"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="16" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.example.externalstorage.MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
Activity class
Let's write the code to write and read data from the android external storage.
File: MainActivity.java
- package com.example.externalstorage;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.Context;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- EditText editTextFileName,editTextData;
- Button saveButton,readButton;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- editTextFileName=(EditText)findViewById(R.id.editText1);
- editTextData=(EditText)findViewById(R.id.editText2);
- saveButton=(Button)findViewById(R.id.button1);
- readButton=(Button)findViewById(R.id.button2);
- //Performing action on save button
- saveButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View arg0) {
- String filename=editTextFileName.getText().toString();
- String data=editTextData.getText().toString();
- FileOutputStream fos;
- try {
- File myFile = new File("/sdcard/"+filename);
- myFile.createNewFile();
- FileOutputStream fOut = new
- FileOutputStream(myFile);
- OutputStreamWriter myOutWriter = new
- OutputStreamWriter(fOut);
- myOutWriter.append(data);
- myOutWriter.close();
- fOut.close();
- Toast.makeText(getApplicationContext(),filename + "
- saved",Toast.LENGTH_LONG).show();
- } catch (FileNotFoundException e) {e.printStackTrace();}
- catch (IOException e) {e.printStackTrace();}
- }
- });
- //Performing action on Read Button
- readButton.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View arg0) {
- String filename=editTextFileName.getText().toString();
- StringBuffer stringBuffer = new StringBuffer();
- String aDataRow = "";
- String aBuffer = "";
- try {
- File myFile = new File("/sdcard/"+filename);
- FileInputStream fIn = new FileInputStream(myFile);
- BufferedReader myReader = new BufferedReader(
- new InputStreamReader(fIn));
- while ((aDataRow = myReader.readLine()) != null) {
- aBuffer += aDataRow + "\n";
- }
- myReader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- Toast.makeText(getApplicationContext
- (),aBuffer,Toast.LENGTH_LONG).show();
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- }
No comments:
Post a Comment