Android Basics – Learn how to create a Started Service using an IntentService

In the last Article you learnt about Android Services and the difference between a bound and a started service. In this Article you will learn how to call the IntentService you created earlier.

To create a started service you need to extend the IntentService class.

public class SampleService extends IntentService

Let’s take a simple example to illustrate how this works.

In the onHandleIntent method you will add a Log.

@Override
protected void onHandleIntent(Intent intent) {
    Log.v(TAG, "In onHandleIntent. Message will be printed after 10sec");
    if (intent != null) {
        synchronized (this){
            try {
                wait(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.v(TAG, "Service started");
        }
    }
}

To call this service you will add a button to the content_main.xml file

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_margin="15dp"
    android:id="@+id/callSampleServiceId"
    android:text="Start Service"
    android:background="@android:color/holo_blue_dark"
    android:textColor="@android:color/white"/>

On click of this button an explicit intent will be called.

if(v.getId() == R.id.callSampleServiceId){
    Log.v(TAG, "Service Button Clicked");

    Intent intent = new Intent(this, SampleService.class);
    startService(intent);
}

View the complete source code here.

Android Basics – Introduction to Services

A Service helps you to execute tasks in the background. Like downloading a file or tracking user location changes.

It is an Application Componenet with no user interface. It has a simple life cycle and comes with a set of features.

There are two types of Services

Bound Service  This kind of service is bound to a component like an Activity and runs as long as the Activity runs.

Started Service  This kind of service can run indefinitely. Even when the Activity that started is is destroyed.

You can create a new service by extending either the Service Class or the IntentService Class.

IntentService allows you to create a started service.

In the video you will learn how to get started by creating an IntentService.

Source Code is available here

Android Basics – Learn how to use an AsyncTask to create a background thread

Like you have seen earlier the code written in the MainActivity class runs in the main thread. If you run the database related code like insert/update etc. on the MainThread then it will slow the App and can lead to bad user experience.

AsyncTask class helps us to overcome this by creating a background thread. Let’s see how to use this.

An AsyncTask has the following methods

  • onPreExecute() : Runs on the main thread and allows you to do initial setup
  • doInBackground() : Runs on a background thread.
  • onPostExecute() : Runs on the Main Thread after the task completes.

Refer to the code segment below in which an inner AsyncTask has been created.

private class SurveyDBAsyncTask extends AsyncTask<String, Void, Long>{

    ContentValues cv;

    @Override
    protected void onPreExecute() {
        Log.v(TAG, "Data entered by the user is "+userNameId.getText()+" "+userAgeId.getText()+" "+userEmailId);

        cv = new ContentValues();
        cv.put(SurveyDBHelper.SURVEY_TABLE_NAME_COLUMN, userNameId.getText().toString());
        cv.put(SurveyDBHelper.SURVEY_TABLE_EMAIL_COLUMN, userEmailId.getText().toString());
        cv.put(SurveyDBHelper.SURVEY_TABLE_AGE_COLUMN, userAgeId.getText().toString());

        super.onPreExecute();
    }

    /**
     * Override this method to perform a computation on a background thread. The
     * specified parameters are the parameters passed to {@link #execute}
     * by the caller of this task.
     * <p/>
     * This method can call {@link #publishProgress} to publish updates
     * on the UI thread.
     *
     * @param params The parameters of the task.
     * @return A result, defined by the subclass of this task.
     * @see #onPreExecute()
     * @see #onPostExecute
     * @see #publishProgress
     */
    @Override
    protected Long doInBackground(String... params) {
        long id = 0;

        try {
            SurveyDBHelper surveyDBHelper = new SurveyDBHelper(MainActivity.this);
            SQLiteDatabase db = surveyDBHelper.getReadableDatabase();

            id = db.insert(SurveyDBHelper.SURVEY_TABLE, null, cv);

            db.close();
        }catch (SQLiteException e){
            Log.v(TAG, "Exception "+e.getMessage());
        }
        return id;
    }

    @Override
    protected void onPostExecute(Long id) {
        super.onPostExecute(id);
    }
}

You can find the complete source code here.

Android Basics – Learn about the changeCursor method to refresh Cursor data

You have seen how to use a Cursor to fetch data from a SQLite database. And then how to use a CursorAdapter to display the data in a ListView.

One problem with a Cursor is that it does not track the database changes. So if the data gets updated a cursor won’t present the updated version until the Activity gets recreated.

To illustrate this I have added a ListView in the layout xml, to display the surveys which have been added to the database.

To overcome this problem in the Activity onRestart method you need to use the changeCursor method. Refer to the below code segment.
Layout XML Code

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/displaySurveyDataId"/>

MainActivity Code

@Override
public void onRestart(){
    super.onRestart();

    Log.v(TAG, "Check for data refresh");

    try {
        SurveyDBHelper surveyDBHelper = new SurveyDBHelper(this);
        SQLiteDatabase db = surveyDBHelper.getReadableDatabase();

        Cursor cursor = surveyDBHelper.getSurveyData(db);

        ListView lv = (ListView) findViewById(R.id.displaySurveyDataId);

        CursorAdapter ca = (CursorAdapter)lv.getAdapter();
        ca.changeCursor(cursor);

    }catch (SQLiteException e){
        Log.v(TAG, "Exception "+e.getMessage());
    }
}

Please follow the video to understand this better. Also the source code is available here for reference.

Android Basics – Learn how to insert records to the SQLite Database

So far you have seen how to fetch data from the SQLite database using Cursor. Inserting and updating data is also pretty simple.

The following code inserts data to the survey table.

try {
    SurveyDBHelper surveyDBHelper = new SurveyDBHelper(this);
    SQLiteDatabase db = surveyDBHelper.getReadableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(SurveyDBHelper.SURVEY_TABLE_NAME_COLUMN, userNameId.getText().toString());
    cv.put(SurveyDBHelper.SURVEY_TABLE_EMAIL_COLUMN, userEmailId.getText().toString());
    cv.put(SurveyDBHelper.SURVEY_TABLE_AGE_COLUMN, userAgeId.getText().toString());

    db.insert(SurveyDBHelper.SURVEY_TABLE, null, cv);

    db.close();
}catch (SQLiteException e){
    Log.v(TAG, "Exception "+e.getMessage());
}

In the above code fragment you need to create a Content Value object which stores key value pairs. This object is then used for insert.

Follow the video to understand this better. The source code is available here for reference.

Android Basics – Learn how to use a CursorAdapter to bind data from a Cursor to a ListView

Suppose you are using a ListView to display a list of items. And these items come from the database. To help you implement this functionality CursorAdapter comes in handy.

It is like a ListAdapter. The difference being that instead of getting data from an Array it gets from the database.

Another advantage of using CursorAdapter is that the number of items it fetches from the database is equal to the number which can be displayed on screen.

So for instance if the table has 100 rows and the app can display only 5 at a time, then CursorAdapter will get only 5 rows.

As the user scrolls it pulls more data. This makes a CursorAdapter efficient.

You will use a SimpleCursorAdapter which implements a CursorAdapter in your App. Let’s see how.

The Constructor which you will be using will look like:

public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to, int flags)

The parameter details are available in Android documentation.

“flags” will be set to 0 for demonstration purpose.

If you are using a CursorAdapter then you do not need to close the cursor and the database. You can do this in the onDestroy lifecycle method.

Source Code is available here

The “Real Man” decoded – Why some colleges are waking up to the fact that men may need to be taught to think beyond their own stereotypes?

Why do we continue to limit the emotional lives of males when it serves no one?

A recent New York Times article takes a dig into the Male psychology and why it’s so hard for them to emote there feelings, unlike Females.

Being a “Male” I can relate to the findings. If you consider India for instance, then from a very young age boys are conditioned (by their families and societies) to become “Strong”.

Being strong means that you should avoid public display of your emotions. You are supposed to be the head of the household. If you cry you will be reminded that  you are a Man, and a Man need not cry.

The emotions dry up gradually only to erupt in other forms. And anger becomes normal.

“Boys’ underperformance in school has more to do with society’s norms about masculinity than with anatomy, hormones or brain structure. In fact, boys involved in extracurricular cultural activities such as music, art, drama and foreign languages report higher levels of school engagement and get better grades than other boys. But these cultural activities are often denigrated as un-masculine by preadolescent and adolescent boys.”

“Bro Code” – The survival kit of many middle-class, white male students: online pornography, binge drinking, a brotherhood in which respect is proportional to the disrespect heaped onto young women during hookups, and finally, the most ubiquitous affirmation of their tenuous power, video games.

Surprisingly what studies have found is that from infancy through age 4 or 5, boys are more emotive than girls. But we socialize this vulnerability out of them.

The Article is worth reading and pondering on. We need to reevaluate things that have become normal and question if it’s of any benefit.

News Source : New York Times