telephone number
0120-6481595, 09999-283-283
  
email address
info(at)sisoft.in

Android Shared Preference Example

Application Description

Create an App to Manage Phone Contacts(Add/Modify/Delete/View).In this example, usage of Shared Preferences has been explained.

Concept Used

1.Data Read and Write in Shared Preferences.

2.Fetch value from Shared Preference File, Store in Hashmap, prepare simple adapter and displaying in listView.

3.Alert Dialog for delete confirmation

4.HashMap

 

Project Structure

Files Used:

1.AndroidManifest.xml

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk 
           android:minSdkVersion="10" />
           android:targetSdkVersion="18" />

    <application

        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.example.addcontact.MainActivity"
            android:label="List Contacts" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.example.addcontact.ActivityOne"
            android:label="Add Contact"/>
    </application>

</manifest>
The manifest file has only two activities. One for taking user input and another for displaying the output.

2.activity_main.xml

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#008000"
    android:orientation="vertical" >
    tools:context="MainActivity" >


   <LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:weightSum="1.20"
    android:orientation="horizontal" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="200dp"
        android:layout_height="20dp"
        android:layout_marginLeft="5dp"
        android:textStyle="bold"
        android:text="NAME" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="100dp"
        android:layout_height="20dp"
        android:textStyle="bold"
        android:text="PHONE" />


    <Button
        android:id="@+id/btn_add"
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="140dp"
        android:gravity="right"
        android:layout_gravity="end"
        android:background="@drawable/add1"
   </LinearLayout>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="100dp"
        android:layout_height="20dp"

</LinearLayout>

3.activityone.xml

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#008000"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="200dp"
        android:layout_height="20dp"
        android:layout_marginLeft="5dp"
        android:textStyle="bold"
        android:text="NAME" />


    <EditText
        android:id=""@+id/edt_name""
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="20dp"
        android:layout_toRightOf="@+id/text_name" />
        ndroid:gravity="center" />
        android:hint="Name" />
        android:textColor="@android:color/black" />
        android:textSize="20sp" />



    <TextView
        android:id="@+id/textView1"
        android:layout_width="200dp"
        android:layout_height="20dp"
        android:layout_marginLeft="5dp"
        android:textStyle="bold"
        android:text="NAME" />

    <EditText
        android:id=""@+id/edt_name""
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="20dp"
        android:layout_toRightOf="@+id/text_name" />
        ndroid:gravity="center" />
        android:hint="Name" />
        android:textColor="@android:color/black" />
        android:textSize="20sp" />

    <Button
        android:id="@+id/btn_clr"
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="140dp"
        android:gravity="right"
        android:layout_gravity="end"
        android:background="@drawable/add1"

    <Button
        android:id="@+id/btn_add"
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="140dp"
        android:gravity="right"
        android:layout_gravity="end"
        android:background="@drawable/add1"
</RelativeLayout>

4.MainActivity.java



package com.example.addcontact;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.example.addcontact.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener{
Button btn_add;
TextView text_view,text_name,text_number;
ListView list_View;
SharedPreferences sp;
SharedPreferences.Editor ed;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		list_View=(ListView)findViewById(R.id.listView1);
		
		   sp = this.getSharedPreferences("Contact List", MODE_PRIVATE);
		    ed = sp.edit();
		    
	        Map map = sp.getAll();

	        List> l1 = new ArrayList>();
	        Set keySet = map.keySet();
	        Iterator iterator = keySet.iterator();
	        
	        while (iterator.hasNext()) {
	            Map newMap = new HashMap();
	            String key = (String) iterator.next();
	            String value = (String)map.get(key);
	            newMap.put("Name", key);
	            newMap.put("Phone", value);

	            l1.add(newMap);
	        }
		
	 SimpleAdapter a1 = new SimpleAdapter(this,l1,R.layout.view_ct,
		 new String[] {"Name", "Phone" },
		 new int[] {R.id.textView1, R.id.textView2});
	list_View.setAdapter(a1);	

	list_View.setOnItemClickListener(this); 
	btn_add=(Button)findViewById(R.id.btn_add);   
	btn_add.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
	Intent i=new Intent(getApplicationContext(),ActivityOne.class);
	startActivity(i);
			
		}
	});	
		}
	@Override
public void onItemClick(AdapterView ? parent, View view, int position, long id) 
{
HashMap selection = (HashMap)
 list_View.getItemAtPosition(position);
String name = selection.get("Name");
String number=selection.get("Phone");
            
"Name is ["+name+"] and Contact number ["+number, Toast.LENGTH_SHORT).show();
ed.remove(name);
 ed.commit();
		
	    
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Confirm Delete...");
 alertDialog.setMessage("Are you sure you want delete this?");
alertDialog.setIcon(R.drawable.ic_launcher);
		 
   alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {

  public void onClick(DialogInterface dialog,int which) {
 Toast.makeText(getApplicationContext(), 
"You clicked on YES", Toast.LENGTH_SHORT).show();
 Toast.makeText(getApplicationContext(),
 "Name is Deleted", Toast.LENGTH_SHORT).show();
	        }
        });
    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), 
"You clicked on NO", Toast.LENGTH_SHORT).show();
              dialog.cancel();
		    }
	    });
	 AlertDialog al = alertDialog.create();
	 al.show();
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	getMenuInflater().inflate(R.menu.main, menu);
	return true;
	}
}

5.ActivityOne.java

package com.example.addcontact;

import java.sql.Savepoint;

import com.example.addcontact.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityOne extends Activity implements OnClickListener{
TextView text_view,text_name,text_number;
EditText edt_name,edt_number;
String name,number;
Button btn_add,btn_clr;

SharedPreferences sp;
Editor ed;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activityone);
		getInit();
	}
	public void getInit() {
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_clr = (Button) findViewById(R.id.btn_clr);
        edt_name = (EditText) findViewById(R.id.edt_name);
        edt_number = (EditText) findViewById(R.id.edt_number);
        btn_add.setOnClickListener(this);
        btn_clr.setOnClickListener(this);
	}
	 
	  @Override
	    public void onClick(View v) {
	        switch (v.getId()) {
	        case R.id.btn_add:
if(edt_name.getText().toString().equals("")||
edt_number.getText().toString().equals(""))
{
Toast.makeText(this, "Enter Name and Number", Toast.LENGTH_LONG).show();
	       		break ;
				}
	          String  name = edt_name.getText().toString();
	           String number =edt_number.getText().toString();
	           sp = getSharedPreferences("Contact List", MODE_PRIVATE);
		        ed = sp.edit();
		        ed.putString(name, number);
		        ed.commit();
		       
                   break;
	          
        case R.id.btn_clr:
    Intent i=new Intent(getApplicationContext(),MainActivity.class);
	startActivity(i);
	          
	        }
	        back();
	  }
	
	  private void back() {
	edt_name.setText("");
	edt_number.setText("");
		
	}
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

ScreenShots

MainActivity.java

ActivityOne.java

About the Contributor...

Ankit Kamboj
   MCA Final Year ITS Mohan Nagar Ghaziabad 
   Trainee at Sisoft Technologies Indirapuram Ghaziabad