Monday 3 November 2014

Android Tutorial 50 : SharedPreferences In Android

In Android there are 3 ways to store/save the data.

1:  Using Database (Creating table)     
2: Using Files
3: Using  SharedPreferences

SharedPreferences


SharedPreferences  Store private primitive data in key-value pairs.
The SharedPreferences class provides a way  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). 


How To Use SharedPreferences:


Get the SharedPreference


SharedPreferences  shfObject = getSharedPreferences("NAME", Context.MODE_PRIVATE); 

Writting Data to SharedPreferences:


We can write boolean, char, String, Int, long or  any type of Data to SharedPreferences and get back the value.

As already discussed that SharedPreferences store data in key value pair.


To write data  to SharedPreference we need  to use  SharedPreferences.Editor    class.

 SharedPreferences.Editor  shfEditorObject=shfObject.edit();

The general format is  to store data in     SharedPreference

shfEditorObject .putDataType("KEYNAME", "VALUE"); 

and do not forget to commit the changes made in SharedPrefenrence by using commit method.

shfEditorObject.commit();
To write a boolean:

shfEditorObject.putBoolean(key, value)
 shfEditorObject.commit();


To write an Int:

shfEditorObject.putInt(key, value)
 shfEditorObject.commit();

To write a String:

shfEditorObject.putString(key, value);
 shfEditorObject.commit();

To write a long:

shfEditorObject.putLong(key, value);
 shfEditorObject.commit();

To write a float:

shfEditorObject.putFloat(key, value);
 shfEditorObject.commit();

Fetch/Retrieve data from  SharedPreferences:


get the   SharedPreferences   with exact same SharedPreferences "NAME"  supplied to store the value

SharedPreferences  shfObject = getSharedPreferences("NAME", Context.MODE_PRIVATE);  

Stored data is fetch using SharedPreference Object, here we will use shfObject to get the data Stored in SharedPreference 

the general format is :

shfObject.getDataType("KEY", defaultedValue);

Please note that the above method return the defaultedValue  if "KEY" does not exist.


To get a boolean value

shfObject.getBoolean(key, defaultValue)



To get an Int value

shfObject.getInt(key, defaultValue)

To get a Long value

shfObject.getLong(key, defaultValue)

To get a String value

shfObject.getString(key, defaultValue)

To get a Float value

shfObject.getFloat(key, defaultValue)



SharedPreferences can be used in the  all the Activities, Broadcast Receivers  within an Application. 



Android Tutorial 49 : Saving Data Using SharedPreferences in Android

In Android there are 3 ways to store/save the data.

1:  Using Database (Creating table)    
2: Using Files
3: Using  SharedPreferences

SharedPreferences


SharedPreferences  Store private primitive data in key-value pairs.
The SharedPreferences class provides a way  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). 


How To Use SharedPreferences:


Get the SharedPreference


SharedPreferences  shfObject = getSharedPreferences("NAME", Context.MODE_PRIVATE); 

Writting Data to SharedPreferences:


We can write boolean, char, String, Int, long or  any type of Data to SharedPreferences and get back the value.

As already discussed that SharedPreferences store data in key value pair.


To write data  to SharedPreference we need  to use  SharedPreferences.Editor    class.

 SharedPreferences.Editor  shfEditorObject=shfObject.edit();

The general format is  to store data in     SharedPreference

shfEditorObject .putDataType("KEYNAME", "VALUE"); 

and do not forget to commit the changes made in SharedPrefenrence by using commit method.

shfEditorObject.commit();
To write a boolean:

shfEditorObject.putBoolean(key, value)
 shfEditorObject.commit();


To write an Int:

shfEditorObject.putInt(key, value)
 shfEditorObject.commit();

To write a String:

shfEditorObject.putString(key, value);
 shfEditorObject.commit();

To write a long:

shfEditorObject.putLong(key, value);
 shfEditorObject.commit();

To write a float:

shfEditorObject.putFloat(key, value);
 shfEditorObject.commit();

Fetch/Retrieve data from  SharedPreferences:


get the   SharedPreferences   with exact same SharedPreferences "NAME"  supplied to store the value

SharedPreferences  shfObject = getSharedPreferences("NAME", Context.MODE_PRIVATE);  

Stored data is fetch using SharedPreference Object, here we will use shfObject to get the data Stored in SharedPreference 

the general format is :

shfObject.getDataType("KEY", defaultedValue);

Please note that the above method return the defaultedValue  if "KEY" does not exist.


To get a boolean value

shfObject.getBoolean(key, defaultValue)



To get an Int value

shfObject.getInt(key, defaultValue)

To get a Long value

shfObject.getLong(key, defaultValue)

To get a String value

shfObject.getString(key, defaultValue)

To get a Float value

shfObject.getFloat(key, defaultValue)



SharedPreferences can be used in the  all the Activities, Broadcast Receivers  within an Application. 


Android Tutorial 48 : Connecting ListView To Database

In this post I will describe how to connect ListView with database. 
ListView can be populated by ArrayAdapter, Custom Adapter, ArrayList etc




ListView with DataBase Example


In this example I have created a listView  and populated it with DataBAse.
Each of the ListView item contain two views
TextView SMS Sender : to show SMS Sender Number
TextView SMSBody : to show the SMS Body/content

Here the ListView shows the all the SMSes with Sender Number and SMSBody.


Add the following permission in your manifest file to read the SMS..
   <uses-permission android:name="android.permission.READ_SMS"/>
   <uses-permission android:name="android.permission.WRITE_SMS"/>


listview_activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D1FFFF"
    android:orientation="vertical">
   
   
    <ListView
        android:id="@+id/listViewSMS"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:dividerHeight="0.1dp"
        android:divider="#0000CC"
        >
    </ListView>
   
  </LinearLayout>



listview_each_item.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textViewSMSSender"
        android:paddingLeft="2dp"
        android:textSize="20dp"
        android:textStyle="bold"
        android:textColor="#0000FF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textViewMessageBody"
        android:paddingLeft="5dp"
        android:textColor="#5C002E"
        android:textSize="17dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>
   
  </LinearLayout>




ListViewWithDatabaseActivity 


public class ListViewWithDatabaseActivity extends Activity 
{

    
        ListView listViewPhoneBook; 
        Context context;
         @Override
        protected void onCreate(Bundle savedInstanceState) 
         {
                 super.onCreate(savedInstanceState);
                 setContentView(R.layout.listview_activity_main);
                 context=this;
                 //get the ListView Reference
                 listViewSMS=(ListView)findViewById(R.id.listViewSMS);
                 

                  //arrayColumns is the column name in your cursor where you're getting the data 
                  // here we are displaying  SMSsender Number i.e. address and SMSBody i.e. body

                  String[] arrayColumns = new String[]{"address","body"};
                  //arrayViewID contains the id of textViews
                  // you can add more Views as per Requirement
                  // textViewSMSSender is connected to "address" of arrayColumns
                  // textViewMessageBody is connected to "body"of arrayColumns

                  int[] arrayViewIDs = new int[]{R.id.textViewSMSSender,R.id.textViewMessageBody};
                     
                     
                  Cursor cursor;
                   
                    cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
                   
                // create an Adapter with arguments layoutID, Cursor, Array Of Columns, and Array of ViewIds which is to be Populated
                   
                 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview_each_item, cursor, arrayColumns, arrayViewIDs);
                 listViewSMS.setAdapter(adapter);
                 
                 
                 
                 // To handle the click on List View Item
                 listViewSMS.setOnItemClickListener(new OnItemClickListener()
                {
                    
                                public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
                                {
                                    // when user clicks on ListView Item , onItemClick is called
                                    // with position and View of the item which is clicked
                                    // we can use the position parameter to get index of clicked item

                                    TextView textViewSMSSender=(TextView)v.findViewById(R.id.textViewSMSSender);
                                    TextView textViewSMSBody=(TextView)v.findViewById(R.id.textViewMessageBody);
                                    String smsSender=textViewSMSSender.getText().toString();
                                    String smsBody=textViewSMSBody.getText().toString();
                                   
                                    // Show The Dialog with Selected SMS
                                    AlertDialog dialog = new AlertDialog.Builder(context).create();
                                    dialog.setTitle("SMS From : "+smsSender);
                                    dialog.setIcon(android.R.drawable.ic_dialog_info);
                                    dialog.setMessage(smsBody);
                                    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
                                            new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which)
                                        {
                                       
                                                dialog.dismiss();
                                                return;
                                    }   
                                    });
                                    dialog.show();
                                }
                                
                            });
             }
 }


ListView with Custom Adapter