Shared Preferences Example - Android


Shared preferences is used to save primitive data like booleans, floats, ints, longs, and strings.These data will persist even when the application is killed.

Here we create an android project where the user is asked to enter username and password in an activity and we provide an option as 'save login'.The login credentials are stored in shared preferences and the data is used again when the user launched the application next time where he does not need to enter the credentials again.If the 'save login' check box is cleared the shared preferences data is removed.

1. Create a new project by going to File -> New Android Project. Fill all the details and name your activity as Login.

2.Once the project is created in Login.java type following code

Login.java

public class Login extends Activity implements OnClickListener {
 private String username, password;
 private Button ok;
 private EditText editTextUsername, editTextPassword;
 private CheckBox saveLoginCheckBox;
 private SharedPreferences loginPreferences;
 private SharedPreferences.Editor loginPrefsEditor;
 private Boolean saveLogin;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.login);

  ok = (Button) findViewById(R.id.buttonLogin);
  ok.setOnClickListener(this);
  editTextUsername = (EditText) findViewById(R.id.editTextUsername);
  editTextPassword = (EditText) findViewById(R.id.editTextPassword);
  saveLoginCheckBox = (CheckBox) findViewById(R.id.saveLoginCheckBox);
  loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
  loginPrefsEditor = loginPreferences.edit();

  saveLogin = loginPreferences.getBoolean("saveLogin", false);
  if (saveLogin == true) {
   editTextUsername
     .setText(loginPreferences.getString("username", ""));
   editTextPassword
     .setText(loginPreferences.getString("password", ""));
   saveLoginCheckBox.setChecked(true);
  }
 }

 public void onClick(View view) {
  if (view == ok) {
   InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
   imm.hideSoftInputFromWindow(editTextUsername.getWindowToken(), 0);

   username = editTextUsername.getText().toString();
   password = editTextPassword.getText().toString();

   if (saveLoginCheckBox.isChecked()) {
    loginPrefsEditor.putBoolean("saveLogin", true);
    loginPrefsEditor.putString("username", username);
    loginPrefsEditor.putString("password", password);
    loginPrefsEditor.commit();
   } else {
    loginPrefsEditor.clear();
    loginPrefsEditor.commit();
   }

   doSomethingElse();
  }
 }

 public void doSomethingElse() {
  startActivity(new Intent(Login.this, Welcome.class));
  Login.this.finish();
 }

}

3. Now we need to create a layout for login screen. Under res/layouts create a new xml file and name it as login.xml( Right Click on res/layout -> New -> Android XML File)

4. In login.xml type following code

<?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="#000"
    android:padding="10dp" >

    <EditText
        android:id="@+id/editTextUsername"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/imageView1"
        android:hint="Username"
        android:imeOptions="actionNext"
        android:inputType="textNoSuggestions" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editTextUsername"
        android:hint="Password"
        android:imeOptions="actionDone"
        android:inputType="textPassword" />

    <CheckBox
        android:id="@+id/saveLoginCheckBox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editTextPassword"
        android:text="Save Login?"
        android:textColor="#FFF" />

    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/saveLoginCheckBox"
        android:layout_marginTop="40dp"
        android:text="Login" />

</RelativeLayout>


5.Once the login button is clicked the new activity 'Welcome' is called.The corresponding java and xml files are as follows.

Welcome.java

public class Welcome extends Activity {
 private SharedPreferences loginPreferences;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.welcome);
  loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
  String un = loginPreferences.getString("username", "");
  TextView tv = (TextView) findViewById(R.id.textView1);
  tv.setText("Welcome:" + un);
 }

}


Welcome.xml

<?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:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>


If you are testing this project in an emulator you can find the preference file in data/data/<your package>/shared_prefs/loginPrefs.xml.Pull the file and you can see the data in shared preference.

Tested in API level 7
 


Android Custom Gallery Example

Create your own gallery within android application.The following code will fetch the images from your SD card and display them in a grid view as thumbnails .On clicking on the thumbnail the image will be displayed in a new screen maximized.You can build on this code as per your requirement.

Now lets start by creating a simple project.


1.Create an android application project
2.Create a class file name 'MainActivity.java' (would be done when the poject is created)

MainActivity.java

public class MainActivity extends Activity {
 private int count;
 private Bitmap[] thumbnails;
 private String[] arrPath;
 private ImageAdapter imageAdapter;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  final String[] columns = { MediaStore.Images.Media.DATA,
    MediaStore.Images.Media._ID };
  final String orderBy = MediaStore.Images.Media._ID;
  Cursor imagecursor = managedQuery(
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
    null, orderBy);
  int image_column_index = imagecursor
    .getColumnIndex(MediaStore.Images.Media._ID);
  this.count = imagecursor.getCount();
  this.thumbnails = new Bitmap[this.count];
  this.arrPath = new String[this.count];
  for (int i = 0; i < this.count; i++) {
   imagecursor.moveToPosition(i);
   int id = imagecursor.getInt(image_column_index);
   int dataColumnIndex = imagecursor
     .getColumnIndex(MediaStore.Images.Media.DATA);
   thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
     getApplicationContext().getContentResolver(), id,
     MediaStore.Images.Thumbnails.MICRO_KIND, null);
   arrPath[i] = imagecursor.getString(dataColumnIndex);
  }
  GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);

  imageAdapter = new ImageAdapter();
  imagegrid.setAdapter(imageAdapter);
  imagecursor.close();
 }

 public class ImageAdapter extends BaseAdapter {
  private LayoutInflater mInflater;

  public ImageAdapter() {
   mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }

  public int getCount() {
   return count;
  }

  public Object getItem(int position) {
   return position;
  }

  public long getItemId(int position) {
   return position;
  }

  public View getView(int position, View convertView, ViewGroup parent) {
   ViewHolder holder;
   if (convertView == null) {
    holder = new ViewHolder();
    convertView = mInflater.inflate(R.layout.galleryitem, null);
    holder.imageview = (ImageView) convertView
      .findViewById(R.id.thumbImage);

    convertView.setTag(holder);
   } else {
    holder = (ViewHolder) convertView.getTag();
   }
   holder.imageview.setId(position);

   holder.imageview.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
     // TODO Auto-generated method stub
     int id = v.getId();
     Intent intent = new Intent(MainActivity.this,
       lastscreen.class);
     intent.setDataAndType(Uri.parse("file://" + arrPath[id]),
       "image/*");
     intent.putExtra("path", arrPath[id]);
     startActivity(intent);
    }
   });
   holder.imageview.setImageBitmap(thumbnails[position]);
   return convertView;
  }
 }

 class ViewHolder {
  ImageView imageview;
 }
}



3.Now design the UI for your gallery with the 'activity_main.xml',and 'galleryitem.xml' files.

activity_main.xml

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

    <GridView
        android:id="@+id/PhoneImageGrid"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:gravity="center"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10dp" />

</RelativeLayout>


galleryitem.xml
<?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">
<ImageView
android:id="@+id/thumbImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
4.Now add a new activity to your application with 'lastscreen.java' and 'lastscreen.xml' to display the image maximized on clicking the thumbnail.

lastscreen.java


public class lastscreen extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.lastscreen);
  Intent in = getIntent();
  String path = in.getStringExtra("path");
  ImageView i = (ImageView) findViewById(R.id.imageView1);
  Bitmap new_image = BitmapFactory.decodeFile(path);
  i.setImageBitmap(new_image);
 }

}
lastscreen.xml

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

<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.72"
android:src="@drawable/ic_launcher"
android:scaleType="fitXY" />

</LinearLayout>

Now run the project to get a similar output(If running in emulato please check that there are images loaded in sd)
Please remove code that closes cursor in Android 4.0 and higher.