Android : Intents & Shared Preferences

Standard

In this example, we are particularly going to learn three things. First about Intents and switching between activities, then about Spinners and about Shared Preferences. So, let’s just say you have created an activity like a Menu and whenever user clicks on Menu’s one of the buttons; next activity is loaded, for example, Options. So, now, how do you switch between activities and return back to the same. Or how do you transfer and carry user data between activities. Today we answer these questions in our Android Series.

An Intent is a messaging object you can use to request an action from another app component. An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an android.app.Activity, broadcastIntent to send it to any interested BroadcastReceivercomponents, and android.content.Context.startService or android.content.Context.bindService to communicate with a background android.app.Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed. So, to create a new Intent :


Intent in=new Intent(MainActivity.this,NextActivity.class);
startActivity(in);

The parameters passed to the Intent() are the application context and the component class that is to be used for the intent. To start this intent we use startActivity() which launches the new activity. Although this won’t work until you specify the accepted intent actions and its parent activity name in your Android Manifest file.


<activity
    android:name="com.shirish.Intent.NextActivity"
    android:label="@string/title_activity_next"
    android:parentActivityName="com.shirish.Intent.MainActivity" >
<meta-data
     android:name="android.support.PARENT_ACTIVITY"
     android:value="com.shirish.Intent.MainActivity" />

Screenshot_2015-01-02-17-32-34

Screenshot_2015-01-02-17-32-41

Now you can specify the startActivity(Intent) inside the onClick() to load the next activity on a button click. In this process, the next problem you will face is passing the user data from one activity to the next activity. Say for example it might be the user’s options or score or information. This can be achieved with the SharedPreferences.
It is an interface for accessing and modifying preference data returned by Context.getSharedPreferences. For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get methods must be treated as immutable by the application.
Now first lets create a file to save the data,
SharedPreferences pref = getApplicationContext().getSharedPreferences(“Options”, MODE_PRIVATE);

Screenshot_2015-01-02-17-32-49

In the SharedPreferences we use the getSharedPreferences() to create a file to save the data in a specific mode. The getSharedPreferences() retrieves and hold the contents of the preferences file , returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other’s edits as soon as they are made. The available Operating modes are; 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions. The bit MODE_MULTI_PROCESS can also be used if multiple processes are mutating the same SharedPreferences file.

To edit our Shared Preferences file, edit() is used to create a new Editor for these preferences, through which you can make modifications to the data in the preferences and automatically commit those changes back to the SharedPreferences object. commit() is used to commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This automatically performs the requested modifications, replacing whatever is currently in the SharedPreferences. You can also use apply() if the return value is not your main concern as commit() returns true if your values were successfully committed. clear() is used to mark in the editor to remove all values from the preferences. Once commit is called, the only remaining preferences will be any that you have defined in this editor. remove(String key) is used to Mark in the editor that a preference value should be removed, which will be done in the actual preferences once commit is called.
To insert the data in the file putInt(key,value), putFloat(key,value), putBoolean(key,value), putString(key,value) can be used for their repective datatypes. Similary getInt(key,value), getFloat(key,value), getBoolean(key,value), getString(key,value) can be used to retrieve the data from the file. But be carefull with your keys as the are the only identifiers for your data and obviously the should be unique. To retrieve the data in some other activity you need to re-declare the SharedPreferences object with the same filename and mode.

Screenshot_2015-01-02-17-32-57
Here I have made this example where user selects his gender and Android version from the Spinners and clicks the Button. On button click next activity is loaded where again with a button click user can view his Spinner selections.

//Main Activity
package com.shirish.Intent;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {
    Button next;
    Spinner gender,android;
    Editor editor;
  @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     next=(Button) findViewById(R.id.next);
     setTitle("Intent 1");
     gender=(Spinner)findViewById(R.id.gender);
     android=(Spinner)findViewById(R.id.android);
     SharedPreferences pref = getApplicationContext().getSharedPreferences("Options", MODE_PRIVATE);
     editor=pref.edit();
     gender.setOnItemSelectedListener(new CustomOnItemSelectedListener());
     next.setOnClickListener(new OnClickListener(){
       public void onClick(View v){
         String gen=gender.getSelectedItem().toString();
         String and=android.getSelectedItem().toString();
         editor.putString("gender", gen);
         editor.putString("android", and);
         editor.commit();
         Toast.makeText(getApplicationContext(), "Settings saved!",Toast.LENGTH_LONG ).show();
         Intent in=new Intent(MainActivity.this,NextActivity.class);
         startActivity(in);
         }
    });
  }
}
//Next Activity
package com.shirish.Intent;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.content.SharedPreferences;
import android.os.Bundle;

public class NextActivity extends ActionBarActivity {
   Button show;
   TextView optiondisp;
   SharedPreferences pref;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_next);
    optiondisp=(TextView)findViewById(R.id.spindisplay);
    setTitle("Intent 2");
    show=(Button)findViewById(R.id.show);
    pref=getApplication().getSharedPreferences("Options", MODE_PRIVATE);
    show.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          String gen=pref.getString("gender", "");
          String and=pref.getString("android", "");
          optiondisp.setText("Gender:"+gen+"\nAndroid:"+and);
          }
     });
 }
}

You may see that I have used here Spinner elements. It is a view that displays one child at a time and lets the user pick among them. The items in the Spinner come from the Adapter associated with this view. Read my Spinner tutorial to learn how Spinners are implemented.

Download The Source code here:
image4233

Advertisements

2 thoughts on “Android : Intents & Shared Preferences

Leave a Comment:

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s