mobile programming lecture 7 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Mobile Programming Lecture 7 PowerPoint Presentation
Download Presentation
Mobile Programming Lecture 7

Loading in 2 Seconds...

play fullscreen
1 / 131

Mobile Programming Lecture 7 - PowerPoint PPT Presentation


  • 191 Views
  • Uploaded on

Mobile Programming Lecture 7. Dialogs, Menus, and SharedPreferences. Agenda. Dialogs Menus SharedPreferences. Android Application Components. Activity 2. Broadcast Receiver 3. Content Provider 4. Service. Dialogs.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Mobile Programming Lecture 7' - deon


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
mobile programming lecture 7

Mobile Programming

Lecture 7

Dialogs, Menus, and SharedPreferences

agenda
Agenda
  • Dialogs
  • Menus
  • SharedPreferences
android application components
Android Application Components
  • Activity

2. Broadcast Receiver

3. Content Provider

4. Service

dialogs
Dialogs
  • A dialog is a small window that appears in front of the current Activity
  • It causes the Activity to lose focus
  • Used for ProgressBars, Alerts, etc
dialogs1
Dialogs
  • onCreateDialog() is called the first time.
  • onPrepareDialog is called every time its opened.
    • without this, it will remain the same as the first time it was opened
dialogs alertdialog
Dialogs - AlertDialog
  • an AlertDialog is an extension of the Dialog class
  • it is capable of constructing most dialog user interfaces and is the suggested dialog type
dialogs alertdialog1
Dialogs - AlertDialog
  • you should use it for dialogs that use any of the following features
    • a title
    • a text message
    • one, two, or three buttons
    • a list of selectable items (with optional checkboxes or radio buttons)
dialogs creating an alertdialog
Dialogs - Creating an AlertDialog

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

dialogs creating an alertdialog1
Dialogs - Creating an AlertDialog

Nothing special here, just an int I use to identify the dialog, because we can have more than one

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

dialogs creating an alertdialog2
Dialogs - Creating an AlertDialog

Override this method of Activity, which is called when you want to show any dialog of the Activity

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

dialogs creating an alertdialog3
Dialogs - Creating an AlertDialog

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

Switch because we can have more than one dialog, meaning we need to check the dialog id

dialogs creating an alertdialog4
Dialogs - Creating an AlertDialog

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

If you want an AlertDialog, you need to build one first

dialogs creating an alertdialog5
Dialogs - Creating an AlertDialog

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

Give the user a message

dialogs creating an alertdialog6
Dialogs - Creating an AlertDialog

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

If true, then the user can press the back button to dismiss the dialog. false would force the user to make an action on the dialog.

dialogs creating an alertdialog7
Dialogs - Creating an AlertDialog

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

Add a button, AND set a listener for when the button is pressed. This is should be the "positive" button, e.g. "Yes", "Absolutely!"

dialogs creating an alertdialog8
Dialogs - Creating an AlertDialog

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

This is the listener for then the "positive" button is pressed, so you should take some kind of action.

dialogs creating an alertdialog9
Dialogs - Creating an AlertDialog

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

The Dialog isn't created until you call create()

dialogs creating an alertdialog10
Dialogs - Creating an AlertDialog

public class MyDialogs extends Activity {

static final int DIALOG_EXIT_ID = 1;

@Override

protected Dialog onCreateDialog(int id) {

Dialog dialog = null;

switch(id) {

case DIALOG_EXIT_ID:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to exit?");

builder.setCancelable(true);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

AlertDialogExample.this.finish();

}

});

dialog = builder.create();

break;

}

return dialog;

}

}

The type of this method is Dialog, so here we return ... the Dialog!

dialogs alertdialog2
Dialogs - AlertDialog

You can add up to 3 buttons on the AlertDialog by calling

  • dialog.setPositiveButton()
    • we just used this one in the previous slides
  • dialog.setNegativeButton()
    • "No", "Cancel"
  • dialog.setNeutralButton()
    • "Remind me Later"
dialogs showing a dialog
Dialogs - Showing a Dialog
  • To show a Dialog on the screen, simply call
    • showDialog(int)

from within your Activity.

  • It takes as parameter the ID of the dialog.
  • You can also call it from within an anonymous inner class
  • Make sure you override the onCreateDialog() method in that Activity!
dialogs showing a dialog1
Dialogs - Showing a Dialog

See AlertDialogExample

dialogs dismissing a dialog
Dialogs - Dismissing a Dialog
  • You don't want to show the Dialog to the user forever!
  • You have to allow the user to close the dialog somehow, even if it's not cancelable
  • You can dismiss the Dialog by calling
    • dismissDialog(int) from within the controlling Activity where the argument is the Dialog ID
    • dismiss() on the Dialog object
      • e.g. dialog.dismiss()
dialogs showing a dialog2
Dialogs - Showing a Dialog

See DismissDialogExample

dialogs alertdialog with a list
Dialogs - AlertDialog with a List
  • Not only buttons!
  • You can also add a list to your AlertDialog
dialogs alertdialog with a list1
Dialogs - AlertDialog with a List

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

dialogs alertdialog with a list2
Dialogs - AlertDialog with a List

We will use this String array for our list

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

dialogs alertdialog with a list3
Dialogs - AlertDialog with a List

This is a method in an Activity class, as in the previous example

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

dialogs alertdialog with a list4
Dialogs - AlertDialog with a List

We're still using an AlertDialog Builder

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

dialogs alertdialog with a list5
Dialogs - AlertDialog with a List

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

This time we call setItems()!

dialogs alertdialog with a list6
Dialogs - AlertDialog with a List

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

First argument should be your list of items

dialogs alertdialog with a list7
Dialogs - AlertDialog with a List

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

There is more than one OnClickListener class!

dialogs alertdialog with a list8
Dialogs - AlertDialog with a List

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

If you want to use both View.OnclickListener (for buttons) and DialogInterface.OnClickListener (for Dialogs), then you need to be more specific here

dialogs alertdialog with a list9
Dialogs - AlertDialog with a List

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

When an item in the list is clicked, Android kindly provides you with the Dialog object itself, as well as the index of the clicked item

dialogs alertdialog with a list10
Dialogs - AlertDialog with a List

String[] countries = new String[]{"Netherlands", "USA", "St. Martin", "Curacao"};

@Override public Dialog onCreateDialog(int id) {

Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Select a Country");

builder.setItems(countries, new DialogInterface.OnClickListener() {

@Override public void onClick(DialogInterface dialog, int index) {

Toast.makeText(getApplicationContext(),

"You selected " + countries[index], Toast.LENGTH_LONG).show(); }

});

return builder.create();

}

Let's not forget to create the Dialog and return it

dialogs alertdialog with a list11
Dialogs - AlertDialog with a List

See AlertDialogListExample

dialogs date timepicker dialogs
Dialogs - Date/TimePicker Dialogs

See DatePickerDialogExample

dialogs custom dialogs seekbar
Dialogs - Custom Dialogs - SeekBar
  • You can create your own Dialog if the standard Android Dialogs are not suitable for your needs
  • For example, there is no SeekBar Dialog, but you can create your own
  • See CustomDialogExample
dialogs dialogfragment
Dialogs - DialogFragment
  • creating Dialogs by using the onCreateDialog() method of an Activity is old school
  • creating Dialogs by using a DialogFragment is new school
dialogs dialogfragment1
Dialogs - DialogFragment
  • DialogFragment also has an onCreateDialog() callback method!
    • i.e., both an Activity and a DialogFragment have an onCreateDialog() callback method
dialogs dialogfragment2
Dialogs - DialogFragment

DialogFragment is slightly different than the other Fragments we've seen so far

  • We don't need to add it to the XML
  • Nor do we need to add it to the UI using a FragmentTransaction
dialogs dialogfragment3
Dialogs - DialogFragment

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(), "dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

dialogs dialogfragment4
Dialogs - DialogFragment

Let's create our Activity first ...

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(), "dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

dialogs dialogfragment5
Dialogs - DialogFragment

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(), "dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

Let's show the Dialog when this Button is clicked!

dialogs dialogfragment6
Dialogs - DialogFragment

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(), "dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

The Button was just clicked at this point, so let's create a new instance of MyDialogFragment, which we will see in a few slides

dialogs dialogfragment7
Dialogs - DialogFragment

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(), "dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

Just call .show() on the Fragment! This time we didn't need to use the FragmentTransaction to add the Fragment

dialogs dialogfragment8
Dialogs - DialogFragment

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(), "dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

Just pass the FragmentManager and it will take care of adding and removing the Fragment for you

dialogs dialogfragment9
Dialogs - DialogFragment

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(),"dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

Second argument is the tag that you want to assign to the Fragment

dialogs dialogfragment10
Dialogs - DialogFragment

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(), "dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

We will get back to this!

dialogs dialogfragment11
Dialogs - DialogFragment

Let's take a look at our DialogFragment

dialogs dialogfragment12
Dialogs - DialogFragment

public class MyDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is a DialogFragment!");

builder.setPositiveButton("OK", new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

MyActivity act= (MyActivity) getActivity();

act.doPositiveClick();

}

});

return builder.create();

}

}

dialogs dialogfragment13
Dialogs - DialogFragment

DialogFragment!

public class MyDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is a DialogFragment!");

builder.setPositiveButton("OK", new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

MyActivity act= (MyActivity) getActivity();

act.doPositiveClick();

}

});

return builder.create();

}

}

dialogs dialogfragment14
Dialogs - DialogFragment

Dialog also has an onCreateDialog(), the proof is in the @Override

public class MyDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is a DialogFragment!");

builder.setPositiveButton("OK", new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

MyActivity act= (MyActivity) getActivity();

act.doPositiveClick();

}

});

return builder.create();

}

}

dialogs dialogfragment15
Dialogs - DialogFragment

This is how we get the Context from within a Fragment, remember!?

public class MyDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is a DialogFragment!");

builder.setPositiveButton("OK", new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

MyActivity act= (MyActivity) getActivity();

act.doPositiveClick();

}

});

return builder.create();

}

}

dialogs dialogfragment16
Dialogs - DialogFragment

public class MyDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is a DialogFragment!");

builder.setPositiveButton("OK", new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

MyActivity act= (MyActivity) getActivity();

act.doPositiveClick();

}

});

return builder.create();

}

}

We need to return a Dialog!

dialogs dialogfragment17
Dialogs - DialogFragment

You've seen this other stuff before!

public class MyDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is a DialogFragment!");

builder.setPositiveButton("OK", new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

MyActivity act= (MyActivity) getActivity();

act.doPositiveClick();

}

});

return builder.create();

}

}

dialogs dialogfragment18
Dialogs - DialogFragment

public class MyDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is a DialogFragment!");

builder.setPositiveButton("OK", new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

MyActivity act= (MyActivity) getActivity();

act.doPositiveClick();

}

});

return builder.create();

}

}

The button in the Dialog has now been clicked! What do we do next?

dialogs dialogfragment19
Dialogs - DialogFragment

public class MyDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is a DialogFragment!");

builder.setPositiveButton("OK", new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

MyActivity act= (MyActivity) getActivity();

act.doPositiveClick();

}

});

return builder.create();

}

}

Let's get a handle on the Activity containing this Fragment

dialogs dialogfragment20
Dialogs - DialogFragment

public class MyDialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is a DialogFragment!");

builder.setPositiveButton("OK", new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

MyActivity act= (MyActivity) getActivity();

act.doPositiveClick();

}

});

return builder.create();

}

}

Let's call our own custom method, doPositiveClick() on the Activity

dialogs dialogfragment21
Dialogs - DialogFragment

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(), "dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

Which takes us back here, back to our Activity.

dialogs dialogfragment22
Dialogs - DialogFragment

public class MyActivity extends Activity {

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

button.setOnClickListener(new OnClickListener() {

@Override public void onClick(View v) {

MyDialogFragment f = new MyDialogFragment();

f.show(getFragmentManager(), "dialog");

}

});

}

public void doPositiveClick() {

Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show();

}

}

Simply make a Toast as evidence that we were successful

dialogs dialogfragment23
Dialogs - DialogFragment
  • Note that we don't need to override onCreateView() or onActivityCreated() methods of a DialogFragment
  • You may choose to override onCreateView() and return a View if you want to create some custom Dialog without using onCreateDialog()
  • I'll leave it up to the Android developer's website to explain it if anyone is interested in doing so
dialogs dialogfragment24
Dialogs - DialogFragment

See FragmentDialogExample

menu options
Menu Options
  • In Android 2.3.x and below, clicking on the dedicated Menu button allows the user to reveal menu options
  • In Android 3.0 and above, the options menu is presented by way of an action bar
    • the dedicated Menu button is deprecated and some devices just do not have one
menu options creating one 2 3 x
Menu Options - Creating one <= 2.3.x
  • Right click on your project > New > Other ...
  • Select Android XML File
  • In the Resource Type drop down list, select Menu
  • Enter a File name and click Finish
  • Click Add ... > Item
  • Edit the id as appropriate, and enter the Title
  • Repeat to add additional menu options
menu options creating one 2 3 x1
Menu Options - Creating one <= 2.3.x

We will use this Menu XML file, main_menu.xml, for our example

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/set_text"

android:title="@string/set_text_opt"/>

<item android:id="@+id/close"

android:title="@string/close_opt" />

</menu>

menu options creating one 2 3 x2
Menu Options - Creating one <= 2.3.x

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.main_menu, menu);

return true;

}

menu options creating one 2 3 x3
Menu Options - Creating one <= 2.3.x

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.main_menu, menu);

return true;

}

Override this Activity method

menu options creating one 2 3 x4
Menu Options - Creating one <= 2.3.x

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.main_menu, menu);

return true;

}

Similar to a LayoutInflater, but for Menus instead

menu options creating one 2 3 x5
Menu Options - Creating one <= 2.3.x

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.main_menu, menu);

return true;

}

Show the Menu now

menu options creating one 2 3 x6
Menu Options - Creating one <= 2.3.x

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.main_menu, menu);

return true;

}

This is the Menu XML file that we created previously

menu options creating one 2 3 x7
Menu Options - Creating one <= 2.3.x

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.main_menu, menu);

return true;

}

This is given as argument to onCreateOptionsMenu, so use it as argument to inflate the menu

menu options creating one 2 3 x8
Menu Options - Creating one <= 2.3.x

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.main_menu, menu);

return true;

}

Return true if you want the menu to be displayed, false if you don't

menu options creating one 2 3 x9
Menu Options - Creating one <= 2.3.x
  • This is enough for the Menu to be displayed on the screen when the user presses the Menu button
  • If you want to take action after an option is selected, then you need to override the onOptionsItemSelected() method of Activity
menu options creating one 2 3 x10
Menu Options - Creating one <= 2.3.x

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.set_text:

TextView tv = (TextView) findViewById(R.id.textView1);

tv.setText("First Option Selected!");

break;

case R.id.close:

Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show();

finish();

break;

}

return true;

}

menu options creating one 2 3 x11
Menu Options - Creating one <= 2.3.x

We override this method of Activity

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.set_text:

TextView tv = (TextView) findViewById(R.id.textView1);

tv.setText("First Option Selected!");

break;

case R.id.close:

Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show();

finish();

break;

}

return true;

}

menu options creating one 2 3 x12
Menu Options - Creating one <= 2.3.x

Which menu item was selected?

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.set_text:

TextView tv = (TextView) findViewById(R.id.textView1);

tv.setText("First Option Selected!");

break;

case R.id.close:

Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show();

finish();

break;

}

return true;

}

menu options creating one 2 3 x13
Menu Options - Creating one <= 2.3.x

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.set_text:

TextView tv = (TextView) findViewById(R.id.textView1);

tv.setText("First Option Selected!");

break;

case R.id.close:

Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show();

finish();

break;

}

return true;

}

Here we just changed the text of a TextView when the item R.id.set_text is selected

menu options creating one 2 3 x14
Menu Options - Creating one <= 2.3.x

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.set_text:

TextView tv = (TextView) findViewById(R.id.textView1);

tv.setText("First Option Selected!");

break;

case R.id.close:

Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show();

finish();

break;

}

return true;

}

Here we close our app when item R.id.close is selected

menu options creating one 2 3 x16
Menu Options - Creating one <= 2.3.x

You can change the menu options that show up at runtime

menu options creating one 3 0
Menu Options - Creating one >= 3.0

For Android 3.0 and higher ...

http://developer.android.com/guide/topics/ui/actionbar.html

context menu
Context Menu
  • A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content.
  • You can provide a context menu for any view, but they are most often used for items in a
    • ListView
    • other view collections in which the user can perform direct actions on each item.
context menu creating one
Context Menu - Creating one

When creating a Context Menu, you can create a Menu XML file in the same way you do for an Options Menu

context menu creating one1
Context Menu - Creating one

We will use the following XML file for our example

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/edit_option" android:title="Edit"></item>

<item android:id="@+id/share_option" android:title="Share"></item>

<item android:id="@+id/delete_option" android:title="Delete"></item>

</menu>

context menu creating one2
Context Menu - Creating one

We will use the following XML file for our example

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/edit_option" android:title="Edit"></item>

<item android:id="@+id/share_option" android:title="Share"></item>

<item android:id="@+id/delete_option" android:title="Delete"></item>

</menu>

All of the callback methods in this example are declared within our ListActivity

context menu creating one3
Context Menu - Creating one

As a reminder,

  • a ListActivity extends Activity
  • it already has a ListView, so you don't need to add one the the Layout XML file
    • you don't even need to use a Layout XML File
    • which means you don't need to call setContentView()
  • You can geta handle on the ListView by simply calling getListView().
context menu creating one4
Context Menu - Creating one

public class ContextMenuExample extends ListActivity {

String[] entries = new String[]{"Martin","Anderson","Junior","George","Dan"};

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

this.setListAdapter(new ArrayAdapter<String>(this,

android.R.layout.simple_list_item_1, entries));

registerForContextMenu(getListView());

}

...

context menu creating one5
Context Menu - Creating one

We will use this String array to populate our List

public class ContextMenuExample extends ListActivity {

String[] entries = new String[]{"Martin","Anderson","Junior","George","Dan"};

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

this.setListAdapter(new ArrayAdapter<String>(this,

android.R.layout.simple_list_item_1, entries));

registerForContextMenu(getListView());

}

...

context menu creating one6
Context Menu - Creating one

public class ContextMenuExample extends ListActivity {

String[] entries = new String[]{"Martin","Anderson","Junior","George","Dan"};

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

this.setListAdapter(new ArrayAdapter<String>(this,

android.R.layout.simple_list_item_1, entries));

registerForContextMenu(getListView());

}

...

Populate the ListView here

context menu creating one7
Context Menu - Creating one

public class ContextMenuExample extends ListActivity {

String[] entries = new String[]{"Martin","Anderson","Junior","George","Dan"};

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

this.setListAdapter(new ArrayAdapter<String>(this,

android.R.layout.simple_list_item_1, entries));

registerForContextMenu(getListView());

}

...

Register the ListView with a Context Menu, now the menu will show up when you long press on the ListView

context menu creating one8
Context Menu - Creating one

public class ContextMenuExample extends ListActivity {

String[] entries = new String[]{"Martin","Anderson","Junior","George","Dan"};

...

@Override

public void onCreateContextMenu(ContextMenu menu, View v,

ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.context_menu, menu);

}

...

onCreate() from previous slide is here

context menu creating one9
Context Menu - Creating one

public class ContextMenuExample extends ListActivity {

String[] entries = new String[]{"Martin","Anderson","Junior","George","Dan"};

...

@Override

public void onCreateContextMenu(ContextMenu menu, View v,

ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.context_menu, menu);

}

...

Override this method. It is called when the Context Menu for View v is being built

context menu creating one10
Context Menu - Creating one

public class ContextMenuExample extends ListActivity {

String[] entries = new String[]{"Martin","Anderson","Junior","George","Dan"};

...

@Override

public void onCreateContextMenu(ContextMenu menu, View v,

ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.context_menu, menu);

}

...

You've seen this before

context menu creating one11
Context Menu - Creating one

public class ContextMenuExample extends ListActivity {

String[] entries = new String[]{"Martin","Anderson","Junior","George","Dan"};

...

@Override

public void onCreateContextMenu(ContextMenu menu, View v,

ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.context_menu, menu);

}

...

onContextItemSelected() on the next slide goes here

context menu creating one12
Context Menu - Creating one

Override this method of Activity

@Override public boolean onContextItemSelected(MenuItem item) {

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null);

switch(item.getItemId()) {

case R.id.edit_option:

/* Edit option selected */

break;

case R.id.share_option:

/* Share option selected */

break;

case R.id.delete_option:

/* Edit option selected */

break;

}

return true;

}

context menu creating one13
Context Menu - Creating one

This Object has information about the Context Menu, NOT the item in the List

@Override public boolean onContextItemSelected(MenuItem item) {

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null);

switch(item.getItemId()) {

case R.id.edit_option:

/* Edit option selected */

break;

case R.id.share_option:

/* Share option selected */

break;

case R.id.delete_option:

/* Edit option selected */

break;

}

return true;

}

context menu creating one14
Context Menu - Creating one

This Object will have information about the item pressed

@Override public boolean onContextItemSelected(MenuItem item) {

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null);

switch(item.getItemId()) {

case R.id.edit_option:

/* Edit option selected */

break;

case R.id.share_option:

/* Share option selected */

break;

case R.id.delete_option:

/* Edit option selected */

break;

}

return true;

}

context menu creating one15
Context Menu - Creating one

We can get a handle on the item in the ListView by using info.position

@Override public boolean onContextItemSelected(MenuItem item) {

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null);

switch(item.getItemId()) {

case R.id.edit_option:

/* Edit option selected */

break;

case R.id.share_option:

/* Share option selected */

break;

case R.id.delete_option:

/* Edit option selected */

break;

}

return true;

}

context menu creating one16
Context Menu - Creating one

info.position tells us which item was pressed, this is how we tell which Menu Item was pressed

@Override public boolean onContextItemSelected(MenuItem item) {

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null);

switch(item.getItemId()) {

case R.id.edit_option:

/* Edit option selected */

break;

case R.id.share_option:

/* Share option selected */

break;

case R.id.delete_option:

/* Edit option selected */

break;

}

return true;

}

context menu creating one17
Context Menu - Creating one

@Override public boolean onContextItemSelected(MenuItem item) {

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null);

switch(item.getItemId()) {

case R.id.edit_option:

/* Edit option selected */

break;

case R.id.share_option:

/* Share option selected */

break;

case R.id.delete_option:

/* Edit option selected */

break;

}

return true;

}

By combining info.position and item.getItemId(), we know the action needs to be performed on the item

context menu creating one18
Context Menu - Creating one

See ContextMenuExample

preferences sharedpreferences
Preferences - SharedPreferences
  • SharedPreferences is 1 of the 5 methods for Data Storage in Android
    • Internal and external storage, remote server, and local database.
    • http://developer.android.com/guide/topics/data/data-storage.html
  • It stores primitive key-value pairs of primitive data types
    • boolean, int, float, long, String
  • Data persists even if your app has been fully terminated
  • SharedPreferences are only available to app that created them!
preferences sharedpreferences1
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

preferences sharedpreferences2
Preferences - SharedPreferences

The desired name of your SharedPreferences file

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

preferences sharedpreferences3
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

You can get a SharedPreferences file by name by calling this method

preferences sharedpreferences4
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

The second argument is the mode

preferences sharedpreferences5
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

If the SharedPreferences file doesn't exist at this point, it will be created for you

preferences sharedpreferences6
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

Try to get the boolean value "silentMode", "silentMode" is the key. You decide on the name of the key. "silentMode" is not a keyword here

preferences sharedpreferences7
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

If the key doesn't exist (could be because the file was just created in the previous line of code), then this will be the value returned

preferences sharedpreferences8
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

An imaginary method that you created to change the volume setting of the device to silent

preferences sharedpreferences9
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

We want data to persist even after the app has been terminated, so let's Override onStop()

preferences sharedpreferences10
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

Get a handle on our SharedPreferences again, which should have the "silentMode" value set at this point

preferences sharedpreferences11
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

If we want to modify the SharedPreferences, we need to use a SharedPreferences Editor

preferences sharedpreferences12
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

Let's set the value value of silentMode to the imaginary boolean value mSilentMode

preferences sharedpreferences13
Preferences - SharedPreferences

public class SharedPrefsExample extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override protected void onCreate(Bundle state){

super.onCreate(state);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

boolean silent = settings.getBoolean("silentMode", false);

setSilent(silent);

}

@Override protected void onStop(){

super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("silentMode", mSilentMode);

editor.commit();

}

}

Don't forget to save your changes to the file!

preferences sharedpreferences14
Preferences - SharedPreferences

See SharedPrefsExample

preferences preferenceactivity
Preferences - PreferenceActivity

If you want to provide the user with a UI for changing preferences, you can use a PreferenceActivity in combination with SharedPreferences

To create a PreferenceActivity, first create a Preference XML file

preferences preferenceactivity1
Preferences - PreferenceActivity
  • File > New > Other > Android XML File
  • Resource Type: Preference
  • Enter the file name, e.g. preferences.xml
  • Root Element: PreferenceScreen
  • Click Add to add various types of Preferences
    • e.g. EditText
  • Expand the Attributes on the right to edit the attributes for your preferences
preferences preferenceactivity2
Preferences - PreferenceActivity

We will use this preferences.xml file for our example

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

<EditTextPreference android:dialogTitle="Username" android:dialogMessage="Please enter your Username" android:summary="Username for logging in to this app" android:title="Username" android:key="username"/>

<CheckBoxPreference android:summaryOff="I do not want your spam" android:key="spam" android:title="Spam" android:summaryOn="Sign me up for spam"/>

</PreferenceScreen>

preferences preferenceactivity3
Preferences - PreferenceActivity

Creating a PreferenceActivity is easy!

preferences preferenceactivity4
Preferences - PreferenceActivity

public class Preferences extends PreferenceActivity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.preferences);

}

preferences preferenceactivity5
Preferences - PreferenceActivity

Extend PreferenceActivity

public class Preferences extends PreferenceActivity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.preferences);

}

preferences preferenceactivity6
Preferences - PreferenceActivity

public class Preferences extends PreferenceActivity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.preferences);

}

From the preferences.xml file we added previously

preferences preferenceactivity7
Preferences - PreferenceActivity

In your main Activity, you can get the Preferences without specifying the name of the XML file

preferences preferenceactivity8
Preferences - PreferenceActivity

public class MainActivity extends Activity {

SharedPreferences mPrefs;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

String username = mPrefs.getString("username","None");

}

}

preferences preferenceactivity9
Preferences - PreferenceActivity

public class MainActivity extends Activity {

SharedPreferences mPrefs;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

String username = mPrefs.getString("username","None");

}

}

This will allow you to access the preference settings, even if you have more than one preference XML file associated with a PreferenceActivity

preferences preferenceactivity10
Preferences - PreferenceActivity

public class MainActivity extends Activity {

SharedPreferences mPrefs;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

String username = mPrefs.getString("username","None");

}

}

These preferences will automatically save when the user interacts with them!

preferences preferenceactivity11
Preferences - PreferenceActivity

See PreferenceActivityExample

preferences preferenceactivity12
Preferences - PreferenceActivity
  • You can also add a Listener for when a Preference has been changed
  • When a Preference is changed, you may need to update certain values tied to these Preferences
preferences preferencefragment
Preferences - PreferenceFragment

Android 3.0 and higher

PreferenceFragment

references
References
  • The Busy Coder's Guide to Android Development - Mark Murphy
  • Android Developers
  • The Mobile Lab at Florida State University