Showing posts with label preferences. Show all posts
Showing posts with label preferences. Show all posts

Passing data in Android using sharedPreferences



For sharing simple data types between Activities or services we can make use or sharedPreferences , in android.

SharedPreferences or preferences are useful for simple dataTypes, where they are stored as Key/Values pairs in a xml file.

The below example will have two simple activities. One for input and the other for output display. We will shared data between the two activities using sharedPreferences.


NOTE: Used android 2.3.3 SDK


Project structure :






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
<?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" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".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>
        <activity android:name=".OutputActivity"
            android:label="Output screen"/>
    </application>

</manifest>



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


2. main.xml (main layout)



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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter the values" />

    <EditText
        android:id="@+id/valueOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/valueTwo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />

    <EditText
        android:id="@+id/valueThree"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />

    <EditText
        android:id="@+id/valueFour"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />

    <Button
        android:id="@+id/buttonID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/submit" />

</LinearLayout>



The main.xml layout has four input fields and a submit button. Each field will be stored using sharedPreferences and then later used in the OutputActivity.


3. output.xml (layout)



 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
<?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/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Output Private"

        android:textAppearance="?android:attr/textAppearanceMedium" />



    <TextView

        android:id="@+id/privateTxt"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceMedium" />



    <TextView

        android:id="@+id/textView2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Output world read"

        android:textAppearance="?android:attr/textAppearanceMedium" />



    <TextView

        android:id="@+id/readTxt"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceMedium" />



    <TextView

        android:id="@+id/textView3"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Output world write"

        android:textAppearance="?android:attr/textAppearanceMedium" />



    <TextView

        android:id="@+id/writeTxt"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceMedium" />



    <TextView

        android:id="@+id/textView4"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Output world read/write"

        android:textAppearance="?android:attr/textAppearanceMedium" />



    <TextView

        android:id="@+id/readWriteTxt"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceMedium" />



</LinearLayout>




The output.xml layout has four textView fields. These four fields will display the four values shared by MainActivity using sharedPreferences.


4. MainActivity.java




  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

 71

 72

 73

 74

 75

 76

 77

 78

 79

 80

 81

 82

 83

 84

 85

 86

 87

 88

 89

 90

 91

 92

 93

 94

 95

 96

 97

 98

 99

100

101

102

103

104

105

106
package com.example.app;



import android.app.Activity;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;





/**

 * 

 *  Activity class which demos the use of sharedPreferences for sharing data among different Activities 

 * 

 * @author Akshat

 *

 */

public class MainActivity extends Activity

{

 

 

 public static final String PREFS_PRIVATE = "PREFS_PRIVATE";

 public static final String PREFS_WORLD_READ = "PREFS_WORLD_READABLE";

 public static final String PREFS_WORLD_WRITE = "PREFS_WORLD_WRITABLE";

 public static final String PREFS_WORLD_READ_WRITE = "PREFS_WORLD_READABLE_WRITABLE";

 public static final String KEY_PRIVATE = "KEY_PRIVATE";

 public static final String KEY_WORLD_READ = "KEY_WORLD_READ";

 public static final String KEY_WORLD_WRITE = "KEY_WORLD_WRITE";

 public static final String KEY_WORLD_READ_WRITE = "KEY_WORLD_READ_WRITE";

 

 

 private SharedPreferences prefsPrivate;

 private SharedPreferences prefsWorldRead;

 private SharedPreferences prefsWorldWrite;

 private SharedPreferences prefsWorldReadWrite;

 

 

 

 

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState)

    {

        super.onCreate(savedInstanceState);

       

        //Set the view for this activity to main.xml

        setContentView(R.layout.main);

       

        //Get hold of the submit button

        Button button = (Button) findViewById(R.id.buttonID);

      

        //Listener added to the submit button

        button.setOnClickListener(new Button.OnClickListener(){



   @Override

   public void onClick(final View v)

   {

    

    //Get the input values

    EditText valueOneTxt = (EditText) findViewById(R.id.valueOne);

    EditText valueTwoTxt = (EditText) findViewById(R.id.valueTwo);

    EditText valueThreeTxt = (EditText) findViewById(R.id.valueThree);

    EditText valueFourTxt = (EditText) findViewById(R.id.valueFour);

    

    

    // Create shared sharedPreferences

    // We created four different sharedPreferences with different modes

    prefsPrivate = getSharedPreferences(MainActivity.PREFS_PRIVATE, Context.MODE_PRIVATE);

    prefsWorldRead = getSharedPreferences(MainActivity.PREFS_WORLD_READ, Context.MODE_WORLD_READABLE);

    prefsWorldWrite = getSharedPreferences(MainActivity.PREFS_WORLD_WRITE, Context.MODE_WORLD_WRITEABLE);

    prefsWorldReadWrite = getSharedPreferences(MainActivity.PREFS_WORLD_READ_WRITE, Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);

    

    

    // To add values to the sharedPreferences, we get editors from the sharedPreferences

    Editor privateEdit = prefsPrivate.edit();

    Editor worldReadEdit = prefsWorldRead.edit();

    Editor worldWriteEdit = prefsWorldWrite.edit();

    Editor worldReadWriteEdit = prefsWorldReadWrite.edit();

    

    

    

    // With the Editor you can set String, boolean, float, int, and long types as key/value pairs

    // We save the four input values into the four different sharedPreferences

    privateEdit.putString(MainActivity.KEY_PRIVATE, valueOneTxt.getText().toString());

    worldReadEdit.putString(MainActivity.KEY_WORLD_READ, valueTwoTxt.getText().toString());

    worldWriteEdit.putString(MainActivity.KEY_WORLD_WRITE, valueThreeTxt.getText().toString());

    worldReadWriteEdit.putString(MainActivity.KEY_WORLD_READ_WRITE, valueFourTxt.getText().toString());

    

    //Commit the sharedPreferences into a file

    privateEdit.commit();

    worldReadEdit.commit();

    worldWriteEdit.commit();

    worldReadWriteEdit.commit();

    

    //Start another activity by passing an explicit intent

    Intent intent = new Intent(MainActivity.this, OutputActivity.class);    

    startActivity(intent);

   }

         

        });

      

    }

}




5. OutputActivity.java


 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
package com.example.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class OutputActivity extends Activity
{
private SharedPreferences prefsPrivate;
private SharedPreferences prefsWorldRead;
private SharedPreferences prefsWorldWrite;
private SharedPreferences prefsWorldReadWrite;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
//Set the view for this activity to output.xml
setContentView(R.layout.output);
// Get hold of sharedPreferences
prefsPrivate = getSharedPreferences(MainActivity.PREFS_PRIVATE, Context.MODE_PRIVATE);
prefsWorldRead = getSharedPreferences(MainActivity.PREFS_WORLD_READ, Context.MODE_WORLD_READABLE);
prefsWorldWrite = getSharedPreferences(MainActivity.PREFS_WORLD_WRITE, Context.MODE_WORLD_WRITEABLE);
prefsWorldReadWrite = getSharedPreferences(MainActivity.PREFS_WORLD_READ_WRITE, Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
//Get hold of output textview - to display values
TextView privateTxt = (TextView) findViewById(R.id.privateTxt);
TextView readTxt = (TextView) findViewById(R.id.readTxt);
TextView writeTxt = (TextView) findViewById(R.id.writeTxt);
TextView readWriteTxt = (TextView) findViewById(R.id.readWriteTxt);
// Set values form sharedPreferences to the textViews
privateTxt.setText(prefsPrivate.getString(MainActivity.KEY_PRIVATE, "NA"));
readTxt.setText(prefsWorldRead.getString(MainActivity.KEY_WORLD_READ, "NA"));
writeTxt.setText(prefsWorldWrite.getString(MainActivity.KEY_WORLD_WRITE, "NA"));
readWriteTxt.setText(prefsWorldReadWrite.getString(MainActivity.KEY_WORLD_READ_WRITE, "NA"));
}
}




When the app is run, sharedPreferences xml files are created under /data/data/PACKAGE_NAME/



-----------------------------------------------------------------------------------------------------------


Screenshots:

MainActivity






OutputActivity