Android (GCM) Push Notification Tutorial – Part 1

In this tutorial, I will show you how to implement push notifications in your native app for android.

Download the required software packages.

  1. Download and install Android Studio and Android SDK.
  2. Android Studio + SDK – http://developer.android.com/sdk/index.html.

Setting up your development environment

Open your Android Studio and choose Start a new Android Studio project.

Start a new Android Studio project

Start a new Android Studio project

Enter your custom Application name, Company Domain and select Project location. Click Next.

Configure your new project.

Configure your new project.

Select Phone and Tablet. Make sure API 15 selected. Click Next.

Configure your new project.

Configure your new project.

Select Blank Activity and click Next.

Add an activity to Mobile.

Add an activity to Mobile.

Click Finish.

Customize the activity.

Customize the activity.

Now we need to get project id from google cloud. Go to  https://console.developers.google.com and create a new project. Click Create Project button and a popup will appear. Enter your project name and click Create. Mine is Native Push.

google cloud create project

google cloud create project

Then you will be direct to this page. Copy out your project number on the top. Click Enable API. Enable Google Cloud Messaging for Android. Click Credentials under APIs and auth on left sidebar.

google developer console API

google developer console API

 

Google Cloud Messaging for Android

Google Cloud Messaging for Android

Go to Credentials page. It’s under APIs & authCredentials.

APIs Credentials

APIs Credentials

Choose Server key.

APIs Credentials - server key

APIs Credentials – server key

Enter your custom Name and click Create.

APIs Credentials - Create server API key

APIs Credentials – Create server API key

Below is API key details for your project. Copy your API key.

APIs Credentials - API keys

APIs Credentials – API keys

Continue…

Develop a simple android mobile app (toDoList) – Part 2

In the first part of the simple android mobile app (toDoList) tutorial series, you covered the basics of setting environment and user interface.

In this second and final part of the tutorial series, we’ll cover Parse integration for each activity classes.

We’ll start where we left off last tutorial, so open your project from last time, or go through the previous tutorial first. http://blog.revivalx.com/2015/06/09/develop-a-simple-android-mobile-app-todolist-part-1/

First, we start from ListActivity where a list of tasks will happen here. Now we need to create a Task class/model. Create a new package to store our model.

Create a new package.

Create a new package.

Enter model for your package name and click OK.

Package name.

Package name.

Then create a java class called Task in model package then replace with this code.

Task.java

public class Task {

    public String taskId;
    public String name;

    public Task(){
        this.taskId = "";
        this.name = "";
    }

    public void setTaskId(String taskId){
        this.taskId = taskId;
    }

    public String getTaskId(){
        return taskId;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

}

Next, we need to create an XML layout that represents the view template for each item in res/layout/item_task.xml. Right click layout folder > New > Layout resource file.

Layout resource file.

Layout resource file.

Enter item_task in File name. Click OK.

New resource file.

New resource file.

Replace with this code.

item_task.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
   <TextView
      android:id="@+id/txtName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Name"
      android:padding="5sp"
      android:textSize="25sp" />
</LinearLayout>

Next, we need to define the adapter to describe the process of converting the Java object to a View (in the getView method). Create a new java class in model package, name it as TasksAdapter.

TasksAdapter

public class TasksAdapter extends ArrayAdapter<Task> {
    public TasksAdapter(Context context, ArrayList<Task> tasks) {
        super(context, 0, tasks);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Task task = getItem(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_task, parent, false);
        }
        TextView txtName = (TextView) convertView.findViewById(R.id.txtName);
        txtName.setText(task.name);
        return convertView;
    }
}

Now, we can use that adapter in the ListActivity to display an array of items into the ListView. Once the adapter is attached, items will automatically be populated into the ListView based on the contents of the array. You can add new items to the adapter at any time with:

ListActivity.java

public class ListActivity extends ActionBarActivity {

    private Button btnCreate;
    private TasksAdapter adapter;
    private ArrayList<Task> arrayOfTasks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        btnCreate = (Button) findViewById(R.id.btnCreate);
        btnCreate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent createActivity = new Intent(getApplicationContext(), CreateActivity.class);
                startActivity(createActivity);

            }
        });

        arrayOfTasks = new ArrayList<Task>();
        adapter = new TasksAdapter(this, arrayOfTasks);
        ListView listView = (ListView) findViewById(R.id.lv_task);
        listView.setAdapter(adapter);

        ParseQuery<ParseObject> query = ParseQuery.getQuery("Task");

        query.findInBackground(new FindCallback<ParseObject>() {
            public void done(List<ParseObject> taskList, ParseException e) {
                if (e == null) {
                    for (ParseObject tasks : taskList) {

                        Task task = new Task();

                        task.setTaskId(tasks.getObjectId());
                        task.setName(tasks.getString("name"));

                        Log.d("name",task.getName());
                        adapter.add(task);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Task task = adapter.getItem(position);

                Intent intent = new Intent(getBaseContext(), UpdateActivity.class);
                intent.putExtra("objectId",  task.getTaskId());
                startActivity(intent);
            }
        });

    }
}

Update activity_list.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.revivalx.androidparsetodolist.ListActivity">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Create Task"
        android:id="@+id/btnCreate"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lv_task"
        android:layout_below="@+id/btnCreate"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Replace with this code for CreateActivity.java.

CreateActivity.java

public class CreateActivity extends ActionBarActivity {

    private TextView txtName;
    private TextView txtDescription;
    private String name;
    private String description;
    private Button btnCreate;
    private Button btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);

        txtName = (TextView) findViewById(R.id.txtName);
        txtDescription = (TextView) findViewById(R.id.txtDescription);

        btnCreate = (Button) findViewById(R.id.btnCreate);
        btnCreate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                name = txtName.getText().toString();
                description = txtDescription.getText().toString();

                if (name.equals("") && description.equals("")) {
                    Toast.makeText(getApplicationContext(),
                            "Please enter name and description",
                            Toast.LENGTH_LONG).show();

                } else {
                    ParseObject task = new ParseObject("Task");
                    task.put("name", name);
                    task.put("description", description);
                    task.saveInBackground();

                    Intent listActivity = new Intent(getApplicationContext(), ListActivity.class);
                    startActivity(listActivity);
                }

            }
        });

        btnBack = (Button) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent listActivity = new Intent(getApplicationContext(), ListActivity.class);
                startActivity(listActivity);

            }
        });
    }

}

Replace with this code for UpdateActivity.java.

public class UpdateActivity extends ActionBarActivity {

    private TextView txtName;
    private TextView txtDescription;
    private Intent intent;
    private Task task;
    private String name;
    private String description;
    private Button btnUpdate;
    private Button btnDelete;
    private Button btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        intent = getIntent();

        task = new Task();
        task.setTaskId(intent.getStringExtra("objectId"));

        txtName = (TextView) findViewById(R.id.txtName);
        txtDescription = (TextView) findViewById(R.id.txtDescription);

        ParseQuery<ParseObject> query = ParseQuery.getQuery("Task");
        query.getInBackground(task.getTaskId(), new GetCallback<ParseObject>() {
            public void done(ParseObject task, ParseException e) {
                if (e == null) {
                    name = task.getString("name");
                    description = task.getString("description");

                    txtName.setText(name);
                    txtDescription.setText(description);

                } else {
                    Toast.makeText(getApplicationContext(),
                            "Something went wrong",
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        btnUpdate = (Button) findViewById(R.id.btnUpdate);
        btnUpdate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                name = txtName.getText().toString();
                description = txtDescription.getText().toString();

                if (name.equals("") && description.equals("")) {
                    Toast.makeText(getApplicationContext(),
                            "Please enter name and description",
                            Toast.LENGTH_LONG).show();

                } else {
                    ParseQuery<ParseObject> query = ParseQuery.getQuery("GameScore");

                    query.getInBackground(task.getTaskId(), new GetCallback<ParseObject>() {
                        public void done(ParseObject task, ParseException e) {
                            if (e == null) {
                                task.put("name", name);
                                task.put("description", description);
                                task.saveInBackground();

                                Intent listActivity = new Intent(getApplicationContext(), ListActivity.class);
                                startActivity(listActivity);
                            } else {
                                Toast.makeText(getApplicationContext(),
                                        "Something went wrong",
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    });


                }

            }
        });

        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                ParseQuery<ParseObject> query = ParseQuery.getQuery("task");
                query.getInBackground(task.getTaskId(), new GetCallback<ParseObject>() {
                    public void done(ParseObject task, ParseException e) {
                        if (e == null) {

                            task.deleteInBackground();

                            Intent listActivity = new Intent(getApplicationContext(), ListActivity.class);
                            startActivity(listActivity);

                        } else {
                            Toast.makeText(getApplicationContext(),
                                    "Something went wrong",
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                });

            }
        });

        btnBack = (Button) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent listActivity = new Intent(getApplicationContext(), ListActivity.class);
                startActivity(listActivity);

            }
        });

    }

}

Update your activity_update.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.revivalx.androidparsetodolist.UpdateActivity">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtName"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:hint="Name"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtDescription"
        android:layout_below="@+id/txtName"
        android:layout_centerHorizontal="true"
        android:hint="Description"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Update Task"
        android:id="@+id/btnUpdate"
        android:layout_below="@+id/txtDescription"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:id="@+id/btnDelete"
        android:layout_below="@+id/btnUpdate"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Back"
        android:id="@+id/btnBack"
        android:layout_below="@+id/btnDelete"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Run your project. I’m using Genymotion. If you don’t have, you can download it here, https://www.genymotion.com/.

Result.

ListActivity.

ListActivity.

CreateActivity.

CreateActivity.

UpdateActivity.

UpdateActivity.

You can download the source code here, https://github.com/datomnurdin/AndroidParseToDoList

Develop a simple android mobile app (toDoList) – Part 1

In this tutorial, I will show you how to create a simple to do list app using android and Parse.

Download the required software packages

Download and install Android Studio and Android SDK.

Android Studio + SDK – http://developer.android.com/sdk/index.html

Setting up your development environment

Open your Android Studio and choose Start a new Android Studio project.

Start a new Android Studio project

Start a new Android Studio project

Enter your custom Application name, Company Domain and select Project location. Click Next.

Configure your new project.

Configure your new project.

Select Phone and Tablet. Make sure API 15 selected. Click Next.

Configure your new project.

Configure your new project.

Select Blank Activity and click Next.

Add an activity to Mobile.

Add an activity to Mobile.

Click Finish.

Customize the activity.

Customize the activity.

Sign up for your new account here, https://www.parse.com/.

Parse

Parse

Click Create a New App.

Create a New App

Create a New App

Go to Keys and save your Application ID and Client Key.

Download Parse SDK (latest Parse-1.9.2) and place it to your libs folder. https://parse.com/downloads/android/Parse/latest

Open build.gradle.

build.gradle.

build.gradle.

Add compile com.parse.bolts:bolts-android:1.+ to your build.gradle and sync.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    compile 'com.parse.bolts:bolts-android:1.+'
    compile fileTree(dir: 'libs', include: 'Parse-*.jar')
}

Your app must request the INTERNET and ACCESS_NETWORK_STATE permissions, if it isn’t doing so already. Add the following lines inside the tag in your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Then, add the following to your in AndroidManifest.xml:

<application
        android:name=".App"

Create a new java class. Right click on com.revivalx.androidparsetodolist package > New > Java Class.

Create a new java class.

Create a new java class.

Name it as App. Click OK.

Create a new java class.

Create a new java class.

Put this to your code.

import android.app.Application; 
import com.parse.Parse; 

public class App extends Application { 

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

        Parse.initialize(this, ApplicationID, ClientKey); // Your Application ID and Client Key are defined elsewhere 
    }
} 

Create a new blank activity. Right click on com.revivalx.androidparsetodolist package > New > Activity > Blank Activity.

Create a new blank activity.

Create a new blank activity.

Name Activity Name as ListActivity and leave it others default value. Click Finish.

Customize the activity.

Customize the activity.

Do it twice for two new blank activities.

Customize the activity.

Customize the activity.

Customize the activity.

Customize the activity.

Your final output.

Android Studio project structure.

Android Studio project structure.

Open activity_list.xml in app > layout > activity_list.xml.

Android Studio project structure (activity_list.xml).

Android Studio project structure (activity_list.xml).

Update activity_list.xml with this one.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.revivalx.androidparsetodolist.ListActivity">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Create Task"
        android:id="@+id/btnCreate"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Detail Task"
        android:id="@+id/btnUpdate"
        android:layout_below="@+id/btnCreate"
        android:layout_centerHorizontal="true" />
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lv_task"
        android:layout_below="@+id/btnUpdate"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
activity_list layout design.

activity_list layout design.

Open activity_create.xml in app > layout >activity_create.xml.

Android Studio project structure (activity_create.xml).

Android Studio project structure (activity_create.xml).

Update activity_create.xml with this one.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.revivalx.androidparsetodolist.CreateActivity">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtName"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:hint="Name"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtDescription"
        android:layout_below="@+id/txtName"
        android:layout_centerHorizontal="true"
        android:hint="Description"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Create Task"
        android:id="@+id/btnCreate"
        android:layout_below="@+id/txtDescription"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Back"
        android:id="@+id/btnBack"
        android:layout_below="@+id/btnCreate"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
activity_create layout design.

activity_create layout design.

Open activity_update.xml in app > layout >activity_update.xml.

Android Studio project structure (activity_update.xml).

Android Studio project structure (activity_update.xml).

Update activity_update.xml with this one.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.revivalx.androidparsetodolist.UpdateActivity">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtName"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:hint="Name"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtDescription"
        android:layout_below="@+id/txtName"
        android:layout_centerHorizontal="true"
        android:hint="Description"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Update Task"
        android:id="@+id/btnUpdate"
        android:layout_below="@+id/txtDescription"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Back"
        android:id="@+id/btnBack"
        android:layout_below="@+id/btnUpdate"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
activity_update layout design.

activity_update layout design.

Delete MainActivity and activity_main.xml.

Delete MainActivity and activity_main.xml.

Delete MainActivity and activity_main.xml.

Go your AndroidManifest.xml, replace .MainActivity with .ListActivity.

<activity
            android:name=".ListActivity"

Update these three classes (ListActivity, CreateActivity and UpdateActivity).

ListActivity

package com.revivalx.androidparsetodolist;

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

public class ListActivity extends ActionBarActivity {

    private Button btnCreate;
    private Button btnUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        btnCreate = (Button) findViewById(R.id.btnCreate);
        btnCreate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent createActivity = new Intent(getApplicationContext(), CreateActivity.class);
                startActivity(createActivity);

            }
        });

        btnUpdate = (Button) findViewById(R.id.btnUpdate);
        btnUpdate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent updateActivity = new Intent(getApplicationContext(), UpdateActivity.class);
                startActivity(updateActivity);

            }
        });
    }
}

CreateActivity

package com.revivalx.androidparsetodolist;

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


public class CreateActivity extends ActionBarActivity {

    private Button btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);

        btnBack = (Button) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent listActivity = new Intent(getApplicationContext(), ListActivity.class);
                startActivity(listActivity);

            }
        });
    }

}

UpdateActivity

package com.revivalx.androidparsetodolist;

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


public class UpdateActivity extends ActionBarActivity {

    private Button btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        btnBack = (Button) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent listActivity = new Intent(getApplicationContext(), ListActivity.class);
                startActivity(listActivity);

            }
        });

    }

}

Next tutorial, http://blog.revivalx.com/2015/06/10/develop-a-simple-android-mobile-app-todolist-part-2/.

Android tabhost tutorial

Container for a tabbed window view. This object holds two children: a set of tab labels that the user clicks to select a specific tab, and a FrameLayout object that displays the contents of that page. The individual elements are typically controlled using this container object, rather than setting values on the child elements themselves.

Reference: http://developer.android.com/reference/android/widget/TabHost.html

What do you need for this tutorial?

Before we can proceed this tutorial, make sure you already setup your android studio and sdk in your machine. http://www.techotopia.com/index.php/Setting_up_a_Windows,_Linux_or_Mac_OS_X_Android_Studio_Development_Environment

After setup completed, open your android studio and select Start a new Android Studio project.

Start a new Android Studio project

Start a new Android Studio project

For Application name, use RevivalxAndroidTabhost and then fill out the Company Domain with your customary values. Click Next.

Configure your new project

Configure your new project

Select Phone and Tablet and set Minimum SDK to API 15. Click Next.

Target Android Devices

Target Android Devices

Select Blank Activity and click Next.

Add an activity to Mobile

Add an activity to Mobile

Leave it all default. Click Finish.

Customize the Activity

Customize the Activity

Wait until it complete building.

Your initialize project will look like this.

Android Studio

Android Studio

Open your MainActivity.java and extend the class from ActionBarActivity

public class HomeActivity extends ActionBarActivity {

Create a new layout name bottom_tabs.xml under res > layout folder and type the following code.

Add new layout.

Add new layout.

Enter File name as bottom_tabs. Click Ok.

New Resource File

New Resource File

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0" />
    </android.support.v4.app.FragmentTabHost>

</LinearLayout>

Create BaseContainerFragment.java by right click on your package folder. Type the following code respectively.

package com.revivalx.revivalxandroidtabhost;

/**
 * Created by MNurdin on 5/8/15.
 */
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

public class BaseContainerFragment extends Fragment {

    public void replaceFragment(Fragment fragment, boolean addToBackStack) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if (addToBackStack) {
            transaction.addToBackStack(null);
        }
        transaction.replace(R.id.container_framelayout, fragment);
        transaction.commit();
        getChildFragmentManager().executePendingTransactions();
    }

    public boolean popFragment() {
        boolean isPop = false;
        if (getChildFragmentManager().getBackStackEntryCount() > 0) {
            isPop = true;
            getChildFragmentManager().popBackStack();
        }
        return isPop;
    }

}

Create a new layout name container_fragment.xml under res > layout folder and type the following code.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container_framelayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


</FrameLayout>

Next create five container fragments by right click on your package folder and create classes and name them as FirstContainerFragment.java, SecondContainerFragment.java, ThirdContainerFragment.java, FourthContainerFragment.java and FifthContainerFragment.java. Type the following code respectively.

Right Click on package folder > New >  Java Class

FirstContainerFragment.java

package com.revivalx.revivalxandroidtabhost;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by MNurdin on 5/8/15.
 */
public class FirstContainerFragment extends BaseContainerFragment {

    private boolean mIsViewInited;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.container_fragment, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!mIsViewInited) {
            mIsViewInited = true;
            initView();
        }
    }

    private void initView() {
        replaceFragment(new FirstFragment(), false);
    }

}

SecondContainerFragment.java

package com.revivalx.revivalxandroidtabhost;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by MNurdin on 5/8/15.
 */
public class SecondContainerFragment extends BaseContainerFragment {

    private boolean mIsViewInited;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.container_fragment, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!mIsViewInited) {
            mIsViewInited = true;
            initView();
        }
    }

    private void initView() {
        replaceFragment(new SecondFragment(), false);
    }

}

ThirdContainerFragment.java

package com.revivalx.revivalxandroidtabhost;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by MNurdin on 5/8/15.
 */
public class ThirdContainerFragment extends BaseContainerFragment {

    private boolean mIsViewInited;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.container_fragment, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!mIsViewInited) {
            mIsViewInited = true;
            initView();
        }
    }

    private void initView() {
        replaceFragment(new ThirdFragment(), false);
    }

}

FourthContainerFragment.java

package com.revivalx.revivalxandroidtabhost;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by MNurdin on 5/8/15.
 */
public class FourthContainerFragment extends BaseContainerFragment {

    private boolean mIsViewInited;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.container_fragment, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!mIsViewInited) {
            mIsViewInited = true;
            initView();
        }
    }

    private void initView() {
        replaceFragment(new FourthFragment(), false);
    }

}

FifthContainerFragment.java

package com.revivalx.revivalxandroidtabhost;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by MNurdin on 5/8/15.
 */
public class FifthContainerFragment extends BaseContainerFragment {

    private boolean mIsViewInited;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.container_fragment, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!mIsViewInited) {
            mIsViewInited = true;
            initView();
        }
    }

    private void initView() {
        replaceFragment(new FifthFragment(), false);
    }

}

Now we need 5 fragments and 5 xml layouts for five tabs. So create five fragments by right click on your package folder and create classes and name them as FirstFragment.java, SecondFragment.java, ThirdFragment.java, FourthFragment.java and FifthFragment.java. Type the following code respectively.

Right Click on package folder > New >  Java Class

Create new java class.

Create new java class.

FirstFragment.java

package com.revivalx.revivalxandroidtabhost;

import com.revivalx.revivalxandroidtabhost.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FirstFragment extends Fragment {

    public FirstFragment() {
        // TODO Auto-generated constructor stub

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.first_layout,
                null);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
    }
    //

}

SecondFragment.java

package com.revivalx.revivalxandroidtabhost;

import com.revivalx.revivalxandroidtabhost.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class SecondFragment extends Fragment {

    public SecondFragment() {
        // TODO Auto-generated constructor stub

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.second_layout,
                null);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
    }
    //

}

ThirdFragment.java

package com.revivalx.revivalxandroidtabhost;

import com.revivalx.revivalxandroidtabhost.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class ThirdFragment extends Fragment {

    public ThirdFragment() {
        // TODO Auto-generated constructor stub

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.third_layout,
                null);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
    }
    //

}

FourthFragment.java

package com.revivalx.revivalxandroidtabhost;

import com.revivalx.revivalxandroidtabhost.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FourthFragment extends Fragment {

    public FourthFragment() {
        // TODO Auto-generated constructor stub

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fourth_layout,
                null);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
    }
    //

}

FifthFragment.java

package com.revivalx.revivalxandroidtabhost;

import com.revivalx.revivalxandroidtabhost.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FifthFragment extends Fragment {

    public FifthFragment() {
        // TODO Auto-generated constructor stub

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fifth_layout,
                null);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
    }
    //

}

Now create 5 xml layouts by right clicking on res/layout > New > Layout XML File and name them as first_layout.xml, second_layout.xml, third_layout.xml, fourth_layout.xml and fifth_layout.xml and type the following code in respective files.

Add New Layout XML

Add New Layout XML

Customize the Activity

Customize the Activity

first_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:text="First Fragment"
        android:padding="15dip"
        android:textSize="18dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

second_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:text="Second Fragment"
        android:padding="15dip"
        android:textSize="18dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

third_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:text="Third Fragment"
        android:padding="15dip"
        android:textSize="18dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

fourth_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:text="Fourth Fragment"
        android:padding="15dip"
        android:textSize="18dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

fifth_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:text="Fifth Fragment"
        android:padding="15dip"
        android:textSize="18dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

Each and every tab needs an icon so design icons for each tab. Design each icon in 64 x 64 px and place them in drawable. Download 5 icons from these link below. Don’t forget to rename it into one_64.png, two_64.png, three_64.png, four_64.png and five_64.png.

  1. https://icons8.com/web-app/10962/1
  2. https://icons8.com/web-app/10914/2
  3. https://icons8.com/web-app/10916/3
  4. https://icons8.com/web-app/10915/4
  5. https://icons8.com/web-app/10953/5
icons8

icons8

Android icon states will be define in xml files with default and hover state configurations. For five icons we need the icon state configuration files. So create five xml files under drawable directory. Right click drawable folder select New > Drawable resource file.

New Drawable resource file.

New Drawable resource file.

Create five xml. Use tab_one.xml, tab_two.xml, tab_three.xml, four_tab.xml and five_tab.xml in File name . Click Ok.

New Resource File

New Resource File

Type the following code for icon states.

tab_one.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use this -->
    <item android:drawable="@drawable/one_64" android:state_selected="true" />
    <!-- When not selected, use that-->
    <item android:drawable="@drawable/one_64" />
</selector>

tab_two.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use this -->
    <item android:drawable="@drawable/two_64" android:state_selected="true" />
    <!-- When not selected, use that-->
    <item android:drawable="@drawable/two_64" />
</selector>

tab_three.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use this -->
    <item android:drawable="@drawable/three_64" android:state_selected="true" />
    <!-- When not selected, use that-->
    <item android:drawable="@drawable/three_64" />
</selector>

tab_four.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use this -->
    <item android:drawable="@drawable/four_64" android:state_selected="true" />
    <!-- When not selected, use that-->
    <item android:drawable="@drawable/four_64" />
</selector>

tab_five.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use this -->
    <item android:drawable="@drawable/five_64" android:state_selected="true" />
    <!-- When not selected, use that-->
    <item android:drawable="@drawable/five_64" />
</selector>

Now open MainActivity.java and type the following code. In the following code we are creating five TabSepcs and adding them to TabHost.

package com.revivalx.revivalxandroidtabhost;

import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;


public class MainActivity extends ActionBarActivity {

    private static final String TAB_1_TAG = "one";
    private static final String TAB_2_TAG = "two";
    private static final String TAB_3_TAG = "three";
    private static final String TAB_4_TAG = "four";
    private static final String TAB_5_TAG = "five";
    private FragmentTabHost mTabHost;
    private Menu mainMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bottom_tabs);
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        Bundle b = new Bundle();
        b.putString("key", "One");
        mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("",getResources().getDrawable(R.drawable.tab_one)),FirstContainerFragment.class, b);

        b = new Bundle();
        b.putString("key", "Two");
        mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("",getResources().getDrawable(R.drawable.tab_two)), SecondContainerFragment.class, b);

        b = new Bundle();
        b.putString("key", "Three");
        mTabHost.addTab(mTabHost.newTabSpec(TAB_3_TAG).setIndicator("",getResources().getDrawable(R.drawable.tab_three)), ThirdContainerFragment.class, b);

        b = new Bundle();
        b.putString("key", "Four");
        mTabHost.addTab(mTabHost.newTabSpec(TAB_4_TAG).setIndicator("",getResources().getDrawable(R.drawable.tab_four)), FourthContainerFragment.class, b);

        b = new Bundle();
        b.putString("key", "Five");
        mTabHost.addTab(mTabHost.newTabSpec(TAB_5_TAG).setIndicator("",getResources().getDrawable(R.drawable.tab_five)), FifthContainerFragment.class, b);

    }

    @Override
    public void onBackPressed() {
        boolean isPopFragment = false;
        String currentTabTag = mTabHost.getCurrentTabTag();
        if (currentTabTag.equals(TAB_1_TAG)) {
            isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
        } else if (currentTabTag.equals(TAB_2_TAG)) {
            isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
        } else if (currentTabTag.equals(TAB_3_TAG)) {
            isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
        } else if (currentTabTag.equals(TAB_4_TAG)) {
            isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_4_TAG)).popFragment();
        } else if (currentTabTag.equals(TAB_5_TAG)) {
            isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_5_TAG)).popFragment();
        }
        if (!isPopFragment) {
            finish();
        }
    }

}

Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.revivalx.revivalxandroidtabhost" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Finally run your project.

Source code: https://github.com/datomnurdin/RevivalxAndroidTabhost