Official Google Blog: Coming soon: make your phone your wallet

Official Google Blog: Coming soon: make your phone your wallet

Reactions: 

Using Android Preferences

We saw before that we can persist an application's data using SQLite database. Android offers another way to store user's data through using preferences.

Android preferences is a key/value entries that store data that can be specific to a certain activity or shared among all activities within the application.
the data are stored in a xml file.

Saving Preferences

We can save preferences in three ways:

  1. Preferences can be retrieved only by a single activity.
  2. Preferences can be shared and retrieved among all activities within the application.
  3. Preferences can be shared and retrieved through all applications on the device.
Saving Activity-level preferences:
to save preferences that are accessed only from a single activity, we do it like this:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=prefs.edit();
        editor.putString("pref 1", "some text");
        
        editor.commit();

we get a SharedPreferences object by calling getPreferences(int mode) method which takes an integer value as a parameter, the mode value can be one of the following:

  1. Context.MODE_PRIVATE (0): a file creating mode that makes the created file only accessible by applications with the same user ID (access the file from the same application context, will desctribe later).
  2. Context.MODE_WORLD_READABLE (1): file mode makes the file readable from other applications.
  3. Context.MODE_WORLD_WRITEABLE (2): file mode allows other applications to write to the file.
then we get an instance of SharedPreferences.Editor and write the preference value with editor.putString(String key, String value) method.
shared preferences allows you to insert preferences using the following methods:
  1. editor.putBoolean(String key, boolean value).
  2. editor.putFloat(String key,float value).
  3. editor.putInt(String key, int value).
  4. editor.putLong(String key, long value)
  5. editor.putString(String key, String value)
then we call edit.commit() to save the preferences to the file. commit returns a boolean indicating the result of saving, true if successful and false if failed.

Reading preferences values:
To read preferences values:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
String val=prefs.getString("pref 1", "some text");
we use sharedpreferences.getString(String key, String defaultValue) (or get boolean/float/int) to return the value stored with a specific key or defaultValue if not found.

Saving Application-level preferences:
to save preferences that can be retrieved from all activities in the application we do it like this:
SharedPreferences prefs= getSharedPreferences("demopref", Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor=prefs.edit();
        editor.putString("demostring", "hello");
        editor.commit();

same as the code above, but the difference is that we give our preferences file a name (demopref in this case) so that other activities can reference that preferences file.
Sharing preferences across applications:


We can store preferences in one application and read them in another application, this is done reading the preferences file by loading them through the first application's context.

let's assume we have two applications:

  1. Application 1 with package name "com.mina.prefdemo".
  2. Application2 with package name "com.mina.demoapp".
If application1 creates a preferences file with the name "demopref" and inserts a String preference with the key/value "demostring/hello".

now we access this file and value from application 2 like this:
Context con;
  try {
   con = createPackageContext("com.minasamy.prefdemo", 0);
   SharedPreferences pref=con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
   String x=pref.getString("demostring", "not found");
   txt.setText(x);
  } catch (NameNotFoundException e) {
   Log.e(Tag, e.toString());
  }

Creating Preferences Activities:
android provides another nice way of presenting and saving preferences. you can create Activities that extend PreferenceActivity.
PreferenceActivity is an activity that displays a set of built-in preferences related widgets that are defined in xml file.

the preference activity can be divided to several PreferenceCategory each containing a set of related preferences.
The preferences widgets that Android provide are:

  1. CheckBoxPreference: displays a check box widget.
  2. EditTextPreference: displays an EditText widget to save user prefs.
  3. RingtonePreference: displays a list with the  ringtones on the device.
  4. ListPreference: displays a list of key/value items.
each one of these preferences widgets is associated with a preference key. it's value is persisted instantly as the widget selection changes.

we can construct our preferences screen xml (saved in res/xml directory) layout like this:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory 
    android:title="Catogory one" 
    android:summary="sample summary">
        <CheckBoxPreference
         android:title="Enable" 
         android:key="pref_enable" 
         android:summary="enables a preference"/>
        <EditTextPreference 
        android:summary="Edit text prefrence" 
        android:title="Edit" 
        android:key="pref_edit"/>
        
        
    </PreferenceCategory>
    <PreferenceCategory 
    android:title="Category2" 
    android:summary="sample summary">
        <RingtonePreference 
        android:key="pref_ring" 
        android:title="Ringtones preference"/>
        
        <ListPreference 
        android:key="pref_list" 
        android:title="List Preference" 
        android:dialogTitle="List Pref Dialog" 
        android:entries="@array/pref_items" 
        android:entryValues="@array/pref_items_values"/>
    </PreferenceCategory>


then from our activity:
public class PrefActivity extends PreferenceActivity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  addPreferencesFromResource(R.xml.prefs);
  
 }
}

and the activity will look like this:





the ListPreference can be associated with String array resources as it's key/value entries
<string-array name="pref_items">
    <item>Item1</item>
    <item>Item2</item>
    <item>Item3</item>
    <item>Item4</item>
    <item>Item5</item>
    </string-array>
    
    <string-array name="pref_items_values">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
    </string-array>


to reference the preference widgets programmatically:
EditTextPreference pref_edit=(EditTextPreference)findPreference("pref_edit");

Reactions: 

The Difference between Handler and AsyncTask


After we saw both Handlers and AsyncTasks a question may evolve: what's the difference between the two and when to use one of them over the other ?

The Handler is associated with the application's main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.

AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.

The answer is that both can be used to update the UI from background threads, the difference would be in your execution scenario. You may consider using handler it you want to post delayed messages or send messages to the <strong>MessageQueue</strong> in a specific order.

You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.

Reactions: 

Google to Unveil Service to Let Users Stream Their Music

Google will announce today on Google I/O 2011 it's long anticipated Cloud-based music service.

Reactions: 

Threading in Android part 2: Async Tasks

In the previous post we saw one way to deal with threads in Android, which is by using Handlers. In this post we'll see how to use another technique which is using AsyncTask class.

AsyncTask is an abstract class that provides several methods managing the interaction between the UI thread and the background thread. it's implementation is by creating a sub class that extends AsyncTask and implementing the different protected methods it provides.

Let's demonstrate how to user AsyncTask by creating a simple activity that has two buttons and a progress bar:
<?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"
  >
  <Button
  android:id="@+id/btn"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Show Progress"
  ></Button>
  <ProgressBar
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/progress"
  style="?android:attr/progressBarStyleHorizontal"
  ></ProgressBar>
  <Button
  android:id="@+id/btnCancel"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Cancel"
  ></Button>
</LinearLayout>
Here we have two buttons: one to start progress and the other to stop it.

Creating the AsyncTask sub class:
The first step in implementing AsyncTask is to create a sub class like this:
class ProgressTask extends AsyncTask<Params, Progress, Result>{
}
The AsyncTask declaration has three Varargs parameters which are:
  1. Params: parameter info passed to be used by the AsyncTask.
  2. Progress: the type of progress that the task accomplishes.
  3. The result returned after the AsyncTask finishes.
These parameters are of type Varargs which provide the flexibility to pass dynamic sized arrays as parameters.

In our example our class will be like this:
class ProgressTask extends AsyncTask<Integer, Integer, Void>{
}

The parameter and the progress are of type Integer and the result is Void as our tasks does not return anthing (returns null).
The second step is overriding the protected methods defined by the AsyncTask class that handle the execution life cycle of the AsyncTask.

We have five methods to implement which are:
  1. onPreExecute: the first method called in the AsyncTask, called on the UI thread.
  2. doInBackground: the method that executes the time consuming tasks and publish the task progress, executed in background thread.
  3. onProgressUpdate: method that updates the progress of the AsyncTask, run on the UI thread.
  4. onPostExecute: the final method that gets called after doInBackground finishes, here we can update the UI with the results of the AsyncTask.
  5. onCancelled: gets called if the AsyncTask.cancel() methods is called, terminating the execution of the AsyncTask.

Starting the AsyncTask:
To start the AsyncTask we create an instance of it, then call the execute() method passing the initial parameters like this:
ProgressTask task=new ProgressTask();
// start progress bar with initial progress 10
task.execute(10);
Implementing the AsyncTask:
class ProgressTask extends AsyncTask<Integer, Integer, Void>{

  @Override
  protected void onPreExecute() {
   // initialize the progress bar
   // set maximum progress to 100.
   progress.setMax(100);

  }

  @Override
  protected void onCancelled() {
   // stop the progress
   progress.setMax(0);

  }

  @Override
  protected Void doInBackground(Integer... params) {
   // get the initial starting value
   int start=params[0];
   // increment the progress
   for(int i=start;i<=100;i+=5){
    try {
     boolean cancelled=isCancelled();
     //if async task is not cancelled, update the progress
     if(!cancelled){
      publishProgress(i);
      SystemClock.sleep(1000);

     }

    } catch (Exception e) {
     Log.e("Error", e.toString());
    }

   }
   return null;
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
   // increment progress bar by progress value
   progress.setProgress(values[0]);

  }

  @Override
  protected void onPostExecute(Void result) {
   // async task finished
   Log.v("Progress", "Finished");
  }

 }

Here are the steps:
  1. onPreExecute() method first gets called initializing the maximum value of the progress bar.
  2. doInBackground(Integer... params) methods gets called by obtaining the initial start value of the progress bar then incrementing the value of the progress bar every second and publishing the progress as long as the async task is not cancelled.
  3. onProgressUpdate(Integer... values) method is called each time progress is published from doInBackground, thus incrementing the progress bar.
  4. onPostExecute(Void result) is called after doInBackground finished execution.
  5. void onCancelled() is called if task.cancel(true) is called from the UI thread. it may interrupt the execution preventing onPostExecute from being executed.

The onClick handler of our buttons is like this:
@Override
 public void onClick(View v) {
  ProgressTask task=new ProgressTask();
  switch(v.getId()){
  case R.id.btn:
   task.execute(10);
   break;
  case R.id.btnCancel:
   task.cancel(true);
   break;
  }

 }

Reactions: 

Threading in Android part 1: Handlers

Multi-Threading concept is essential in most platforms. it provides maximum

utilization of the processor. threading is used when the program executes

time consuming processes (such as calling a web service) and to give a

good user experience by unblocking the UI.

Android provides threading techniques to perform time consuming tasks in a

background thread with coordination with the UI thread to update the UI.

Android provides the following methods of threading:
  1. Handlers.
  2. Async. Tasks.
Handlers:
When you create an object from the Handler class, it processes

Messages and Runnable objects associated with the

current thread MessageQueue. the message queue holds the

tasks to be executed in FIFO (First In First Out) mannser. you will need

only ine Handler per activity where the background thread will

communicate with to update the UI.

The Handler is associated with the thread from which it's been created

We can communicate with the Handler by two methods:
  1. Messages.
  2. Runnable objects.
In this post we will demonstrate how to use both using a simple example which is

updating the text of a TextView using multiple threads.

Using Messages:

the steps of using a Handler are as follows:
  1. You create a Handler object with an asscociated callback

    method to handle the received messages (it is the method where the UI update

    will be done).
  2. From the background thread you will need to send messages to the

    handler.
Here's the code of our activity:
public class MainActivity extends Activity {
TextView txt;
// our handler
 Handler handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
//display each item in a single line
  txt.setText(txt.getText()+"Item "+System.getProperty("line.separator"));
     }
 };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  txt=(TextView)findViewById(R.id.txt);
 }
 
 @Override
 protected void onStart() {
  super.onStart();
              // create a new thread
  Thread background=new Thread(new Runnable() {
   
   @Override
   public void run() {
    for(int i=0;i<10;i++)
    {
     try {
      Thread.sleep(1000);        b.putString("My Key", "My Value: 

"+String.valueOf(i));
// send message to the handler with the current message handler          

handler.sendMessage(handler.obtainMessage());
     } catch (Exception e) {
      Log.v("Error", e.toString());
     }
    }
   }
  });
  
  background.start();
 }
}
after running the following code the TextView will display the following,

each second a new line is written:

This example is pretty basic, it just sends the same message for a number of

times.
what if we want the message sent to hold data that's changed each time the

message is sent, the answer is to use Message.setData(Bundle bundle)

method by creating a Bundle object and adding the data to it like this:
public class MainActivity extends Activity {
 TextView txt;
 // our handler
 Handler handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
   // get the bundle and extract data by key
   Bundle b = msg.getData();
   String key = b.getString("My Key");
   txt.setText(txt.getText() + "Item " + key
   +System.getProperty("line.separator"));
  }
 };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  txt = (TextView) findViewById(R.id.txt);
 }

 @Override
 protected void onStart() {
  super.onStart();
  // create a new thread
  Thread background = new Thread(new Runnable() {

   @Override
   public void run() {
    for (int i = 0; i < 10; i++) {
     try {
      Thread.sleep(1000);
                                        Message msg = new Message();
      Bundle b = new Bundle();
      b.putString("My Key", "My Value: " + String.valueOf(i));
      msg.setData(b);
      // send message to the handler with the current message handler
      handler.sendMessage(msg);
           } catch (Exception e) {
      Log.v("Error", e.toString());
     }
    }
   }
  });

  background.start();
 }
}
we put a string to the bundle and send a message with that bundle. in the

handler method we receive the bundle and get the value with the predefined key.
after executing that code the text view would look like this:

Using Runnables:
another way to use Handlers is to pass them a Runnable by using the

Handler.post() method like this:
Runnable r=new Runnable() {
   
   @Override
   public void run() {
    txt.setText("Runnable");
    
   }
  };
  
  handler.post(r);

this will add the Runanble object to the message queue to be executed by

the handler.

Sending Messages in a

timely manner:
we can use handlers to send messages or post runnables at time intervals using

the following methods:

  1. handler.sendEmptyMessageAtTime(int what,long uptimeMillis):sends an
     empty message at a specific time in milli-seconds, can be defined by using the
    SystemClock.uptimeMillis() method to get the time since the device boot
     in milli-seconds and concatinating to it.
  2. handler.sendEmptyMessageDelayed(int what,long delayMillis):sends an
     empty message after a certain amount of time in milli-seconds.
  3. handler.sendMessageAtTime(Message msg,long uptimeMillis).
  4. handler.sendMessageDelayed(Message msg,long delayMillis).
  5. handler.postAtTime(Runnable r,long uptimeMillis).
  6. handler.postAtTime(Runnable r,Object token,long uptimeMillis):posts a
     runnable with an object as a distinguishing token.
  7. handler.postDelayed(Runnable r,long delayMillis).
All the above messages return a boolean indicating whether the message or the

runnable has been placed successfully in the message queue.

Removing Call backs:
if you want to remove a runnable or a message from the message queue, you can

use the following methods:

  1. handler.removeCallbacks(Runnable r).
  2. handler.removeCallbacks(Runnable r,Object token).
  3. handler.removeCallbacksAndMessages(Object token).
  4. handler.removeMessages(int what).
  5. handler.removeMessages(int what,Object object)

Reactions: