Click here to Skip to main content
14,110,477 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

25.7K views
36 bookmarked
Posted 31 May 2015
Licenced CPOL

Create and Publish Your First Android App – Part 1

, 31 May 2015
Rate this:
Please Sign up or sign in to vote.
Today, I am beginning a four part Android tutorial series where I will provide step by step guide on how to create and publish your first Android app.

Today, I am beginning a four part Android tutorial series where I will provide step by step guide on how to create and publish your first Android app. Are you ready to build your first Android app? Great choice! – what do you want to build? For this tutorial series I will be building a demo app called Attendance App.

Imagine a friend of yours came to you and said “I need an Android app that will help me record the attendance for my up coming event”. How will you proceed to build and publish an app like this for your friend. Well, I will show you how in 4 blog post – please be informed that each of these posts are long posts.

  1. Post 1 – Planning: In Post 1 which is this post, I will walk you through how to translate this one line statement into a features list for an app and then create the skeleton of that App including Navigation Drawer, consider this first tutorial an introduction to Material Design.
  2. Post 2- Implement Data Persistence: Every business/productivity app needs some form of data persistence so in the second post I will provide an introduction to SQLite and then steer you towards an ORM which will make life so much easier for you.
  3. Post 3 – Implement Business Logic: In this post we will implement all the features of the app including an attempt on user interface design even though we are not designers.
  4. Post 4 – Publish the App: Your friend will not get their Attendance app you are building unless you publish it, so in this post I will walk you through the publishing process including an overview of internationalization and translation.

Planning your first Android App

The take away I want you to get from this first post is to see how a problem description is translated into a software product an app in this case. In reality what we are trying to do is to use software engineering (Android app in this case) to solve a real world problem which in this case is to create an Attendance recording app. According to John Sonmez of SimpleProgrammer.com “All software is designed to solve some user problem” and it should be, we should not program for programming sake.

Let us revisit your friends request again “I need an Android app that will help me record the attendance for my up coming event” , in traditional software development this is called a Use Case or more accurately a User Story if you follow the agile pattern of software development.

Now look at that sentence again, how many nouns do you see in that one line, or more technically correct how many domain objects do you see in that sentence, those will form the classes in our app and ultimately the screens in our app. To start with there is your imaginary friend whom we will refer to as the Organizer going forward, then there are his/her guests whom we will refer to as the Attendants going forward, then there is the actual Event.

What other domain objects do you see? we have Organizer, Attendants, Event – those are the explicit domain objects, there are also objects that are implied which include Registration and Attendance. The core of the app is Attendance – that is the focus of the app – to record attendance. The organizer need to be able to see the number of guest he/she had for the event and this report is derived from the Attendance log. An app does not have much value if it is just developed for one time use, apps are normally developed for re-usability and one way to achieve this in Android is through settings or more accurately preferences. So we will have to add settings to our app so the Organizer can re-use the app for his next event or in the miminum provide some personalization to the app.  So in summary we have identified the following domain objects

  1. Organizer
  2. Attendants
  3. Events
  4. Registration
  5. Attendance
  6. Settings

Translate Domain Objects to Android App Screens

Now let us translate these domain objects to Android screens, this is a skill you will get better and better at over time as you build more apps. As with all things in software development, there are always more than one way to accomplish a task and the following is my approach which may differ from another person’s approach.

Activities and Fragments

Now that we are talking about Android App screens, I am hoping that you are familiar with Activity and Fragment. If you are not, you may want to go to the Android developer site and read the fundamentals

In my post on Tips for building your first Android app, I mentioned that it helps to limit the number of screens for your first app to 5 and that is what I will do in this post and here are the screens that I come up with.

  1. Main Activity
    1. Attendants List Fragment
    2. Registration Fragment
    3. Event List Fragment
    4. Event Setup Fragment
    5. Report Fragment
  2. Settings Activity
    1. Preference Fragment

Why two Activities? you may ask, we can certainly host our Fragments in one Activity but I have chosen two Activities for the following reason:

  1. Start another Activity: Starting another Activity from an Activity is one of the fundamentals of Android development and I felt is is important to demonstrate that.
  2. Some of the core components we will be using to build our NavigationDrawer (RecyclerView, DrawerLayout, ActionBarDrawerToggle) are defined in the Support library while the PreferenceFragment only exist in the Framework API. Because of this our Fragments that need the Navigation drawer will have to be derived from  android.support.v4.app.Fragment while the Fragment Preference Activity derives from android.app.Fragment; therefore  we cannot use the same FragmentManager to manage all the Fragments. We will use getFragmentManager to manage the PreferenceFragment while we use getSupportFragmentManager to manage the rest of the Fragments.

Project Creation

Lets create the project, shall we! This is what we will accomplish in the remainder of this tutorial:

Navigation Drawer with Material Design

  1. Step 1: Create new Android Studio project – select the blank template, should be the first option
  2. Step 3: Add a package called “Activities”
    1. Move MainActivity.java to the Activities package (right click -> refactor -> move > choose package)
    2. Add PreferenceActivity.java to the Activities package
    3. Make sure that both MainActivity.java and PreferenceActivity.java inherit from AppCompactActivity and not ActionBarActivity since it is deprecated.
  3. Step 3: Add a package called “Fragments”
    1. Inside this Fragments package add the following blank Fragments (dis-select “Include fragment factory method” and “include interface callbacks”)
      1. AttendantsFragment.java
      2. RegistrationFragment.java
      3. ReportFragment.java
      4. EventListFragment.java
      5. EventDetailsFragment.java
    2. Ensure that you changed all the above Fragments to inherit from android.support.v4.Fragment and not android.app.Fragment
  4. Step 4: Add source control – click on tools -> VCS -> Enable Git Integrations, after that you need to add and commit what you have worked on so far and then try to commit as often as you can. If you are not familiar with how to use Git in Android Studio, then checkout this post by Mark Winterbottom.
  5. Step 5: Choose Material Design Color – from http://www.materialpalette.com/ I mentioned that post is a gentle introduction to material design, and bright bold color is one of the hallmarks of material design. Take a look at the screenshot above again, notice the colored ToolBar and the header background behind a picture of me, those are colors from the  http://www.materialpalette.com/ so head over there and play with color combinations, pick anyone you like, do not over think it, it can always be changed. Download the xml color to your computer and go to the next step.
  6. Step 6: Add Color Resource – under res/value create color.xml file and add the color resources that you downloaded from step 5 above and your color.xml will look like this:
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <!--Get colors from: http://www.materialpalette.com/-->
        <color name="primary">#3F51B5</color>
        <color name="primary_dark">#303F9F</color>
        <color name="primary_light">#C5CAE9</color>
        <color name="accent">#FF5252</color>
        <color name="primary_text">#212121</color>
        <color name="secondary_text">#727272</color>
        <color name="icons">#FFFFFF</color>
        <color name="divider">#B6B6B6</color>
    </resources>
     
  7.  Step 7: Add ToolBar – we are going to add material design toolbar using the material design color that you choose above and below are the steps to add toolbar:
    1. Remove old ActionBar – update your styles.xml in res/value to remove the old ActionBar, it is no longer needed as we are going to replace it with Toolbar.
      <resources>
          <!-- Base application theme. -->
          <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
              <!-- Customize your theme here. -->
              <item name="colorPrimary">@color/primary</item>
              <item name="android:windowActionBar">false</item>
          </style>
      </resources>
       
    2. Add ToolBar layout – under res/layout create a layout resource file called toolbar.xml and add the following content within it:
      <?xml version="1.0" encoding="utf-8"?>
      <android.support.v7.widget.Toolbar
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:id="@+id/toolbar"
          android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:minHeight="?attr/actionBarSize"
          android:background="?attr/colorPrimary"/>
       
    3. Add ToolBar layout to MainActitivity Layout – we can now include our new toolbar.xml in our MainActivity layout, and if we add more activities we can simply reuse the same toolbar layout file. You can go ahead and do the same for the PreferenceActivity layout file that you created in Step 3. Your main_activity.xml should look like this:
      <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"
        tools:context=".MainActivity">
      
          <include layout="@layout/toolbar" />
      
          <TextView
              android:layout_below="@+id/toolbar"
              android:text="@string/hello_world"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content" />
      
      </RelativeLayout>
       
    4. Add ToolBar to MainActivity – in the MainActitivity Java code, first add a private toolbar property and then bind that toolbar property to the toolbar layout file that you created. Then set the toolbar property that you created to be the ActionBar of the MainActivity. The top of your MainActivity.java should look like this:
      public class MainActivity extends AppCompatActivity {
          private Toolbar mToolbar;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              mToolbar = (Toolbar)findViewById(R.id.toolbar);
      
              setSupportActionBar(mToolbar);
          }
       
    5. You should now be able to run your app and it should have a ToolBar similar to thisMaterial Design ToolBar Example
  8. Step 8: Add Navigation Drawer – and here comes the most intriguing kid on the block; navigation drawer has always been a challenging concept to implement and material design does not make it any easier with RecylcerView, Layout Manager and RecyclerView adapter. Please follow these 15 steps below to setup Navigation and let me know if you need any clarification.
    1. Create another package in the project called Models
    2. Add a Java class file called DrawerItems.java to the Models package and here are the contents of that file, this is a simple class that defines each row in our navigation drawer
      public class DrawerItem {
          String ItemName;
          int imgResID;
      
          public DrawerItem(String itemName, int imgResID) {
              super();
              ItemName = itemName;
              this.imgResID = imgResID;
          }
      
          public String getItemName() {
              return ItemName;
          }
          public void setItemName(String itemName) {
              ItemName = itemName;
          }
          public int getImgResID() {
              return imgResID;
          }
          public void setImgResID(int imgResID) {
              this.imgResID = imgResID;
          }
      }
       
    3. At the top of the MainActivity.java add the following properties
      1. public String HEADER_NAME = “Your Name”; (that shows your name in the navigation header)
      2. public String HEADER_EMAIL = “Your Email”;
      3. public int HEADER_IMAGE = 1; (we will change this later to point to a resource file)
    4. I have mentioned RecyclerView a few times without explaining what it is, RecyclerView is a more flexible version of ListView that was introduced as part of material design. RecyclerView has an external dependency so we have to add that dependency. Also you noticed the circle image of my picture I showed above, we also need to add another external library that provides that circle image functionality. In your build.gradle file add
      1. compile ‘com.android.support:recyclerview-v7:22.1.1′
      2. compile ‘de.hbdodenhof:circleimageview:1.3.0′
    5. At the top of the Main Activity under the HEADER_IMAGE add the following lines
      private RecyclerView mRecyclerView;
          private RecyclerView.LayoutManager mLayoutManager;
          private DrawerLayout Drawer;
          private ActionBarDrawerToggle mDrawerToggle;
          private List<DrawerItem> dataList;
      <form action='//valokafor.us4.list-manage.com/subscribe/post?u=0600ce94a59d7720819aa3dd8&id=6e5492cf7d' class='frm' method='post'><input type='text' placeholder='Email Address' name='EMAIL' /><input type='text' placeholder='First Name' name='FNAME' /><input type='hidden' name='b_0600ce94a59d7720819aa3dd8_6e5492cf7d' value='' />
      <input type='submit' value="I want to get more tutorials">
      </form>
    6. In the project add a package called Adapters, and under the Adapters package add a Java class file called NavDrawerAdapter.java this is where we will implement that adapter that will manage our NavigationDrawer.
    7. Under res/layout add layout resource file named  nav_bar_row.xml – each of the item in our NavigationDrawer has two items an image and a text, and this xml file defines the layout for each row. Here is the content of this file
    8. Under res/layout add a layout resource file named header.xml and enter the content below; this layout file defines the header above the NavigationDrawer. The background can be any color of your choice. What did was go to http://www.materialpalette.com/ picked a blue color and using snipping tool in windows I took a little screen shot of that blue color, saved it to my res/drawable folder and used it as the background for my header.xml, you can find that background file here
    9. Add icons – again, as you have seen in the screenshot I showed at the beginning, each item in the navigation drawer has an item and icon. Its up to you what Icon you use, Here are few places where you can get icons for your Android project, the icons I used for this project is from icons4android.com. Whatever icons you select, add them to your res/drawables folder. Remember to add all the resolutions hdpi. xhdpi, etc
      1. http://romannurik.github.io/AndroidAssetStudio
      2. http://www.icons4android.com/
      3. http://www.androidicons.com/
    10. At the button of Main Activity add a method addItemsToDataList and here is the content of this method, and this should be after you have added your icons to the drawables folder, this method creates list of the items you want to add to your NavigationDrawer
      private void addItemsToDataList(){
              dataList.add(new DrawerItem(getString(R.string.title_attendants), R.drawable.ic_action_attendants_list));
              dataList.add(new DrawerItem(getString(R.string.title_events), R.drawable.ic_action_events_list));
              dataList.add(new DrawerItem(getString(R.string.title_registration), R.drawable.ic_action_registration));
              dataList.add(new DrawerItem(getString(R.string.title_reports), R.drawable.ic_action_report));
              dataList.add(new DrawerItem(getString(R.string.title_settings), R.drawable.ic_action_settings));
          }
       
    11. Add two strings items to your res/value/string.xm Open Navigation Drawer and Close Navigation Drawer
      <string name="navigation_drawer_close">Close Navigation Drawer</string>
          <string name="title_activity_preference">PreferenceActivity</string>
       
    12. Update activity_main.xml in the layout folder to include DrawerLayout and RecyclerView and this is what your activity_main.xml should now look like
      <?xml version="1.0" encoding="utf-8"?>
      
      <android.support.v4.widget.DrawerLayout
      
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/DrawerLayout"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:elevation="7dp">
      
          <LinearLayout
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
      
              <include android:id="@+id/toolbar" layout="@layout/toolbar" />
      
              <FrameLayout
                  android:id="@+id/container"
                  android:layout_width="match_parent"
                  android:clickable="true"
                  android:layout_height="match_parent"/>
          </LinearLayout>
      
      
          <android.support.v7.widget.RecyclerView
              android:id="@+id/RecyclerView"
              android:layout_width="320dp"
              android:layout_height="match_parent"
              android:layout_gravity="left"
      
              android:background="#ffffff"
              android:scrollbars="vertical">
      
          </android.support.v7.widget.RecyclerView>
      </android.support.v4.widget.DrawerLayout>
       
    13. Now re-open your blank navdraweradapter.java, open this Github gist and copy and paste its content into the navdraweradapter.java, to learn more about  material design Navigation drawer checkout this post by Akash Bangad
    14. Now update your MainActivity.java file to look like this
      public class MainActivity extends AppCompatActivity {
          private Toolbar mToolbar;
      
          public String HEADER_NAME = "Val Okafor";
          public String HEADER_EMAIL = "valokafor@someemail.com";
          public int HEADER_IMAGE = R.drawable.val_okafor;
      
          private RecyclerView mRecyclerView;
          private RecyclerView.LayoutManager mLayoutManager;
          private DrawerLayout Drawer;
          private ActionBarDrawerToggle mDrawerToggle;
          private List<DrawerItem> dataList;
          private RecyclerView.Adapter mAdapter;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              mToolbar = (Toolbar)findViewById(R.id.toolbar);
              setSupportActionBar(mToolbar);
      
              mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
              mRecyclerView.setHasFixedSize(true);
      
              dataList = new ArrayList<DrawerItem>();
              addItemsToDataList();
      
              mAdapter = new NavDrawerAdapter(dataList, this, HEADER_NAME, HEADER_EMAIL, HEADER_IMAGE);
      
              mRecyclerView.setAdapter(mAdapter);
      
              mLayoutManager = new LinearLayoutManager(this);
              mRecyclerView.setLayoutManager(mLayoutManager);
              Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
              mDrawerToggle = new ActionBarDrawerToggle(this, Drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
                  @Override
                  public void onDrawerOpened(View drawerView) {
                      super.onDrawerOpened(drawerView);
                  }
      
                  @Override
                  public void onDrawerClosed(View drawerView) {
                      super.onDrawerClosed(drawerView);
                  }
              };
              Drawer.setDrawerListener(mDrawerToggle);
              mDrawerToggle.syncState();
              //onTouchDrawer(currentFragment);
      
          }
      
          @Override
          public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.menu_main, menu);
              return true;
          }
      
          @Override
          public boolean onOptionsItemSelected(MenuItem item) {
              // Handle action bar item clicks here. The action bar will
              // automatically handle clicks on the Home/Up button, so long
              // as you specify a parent activity in AndroidManifest.xml.
              int id = item.getItemId();
      
              //noinspection SimplifiableIfStatement
              if (id == R.id.action_settings) {
                  return true;
              }
      
              return super.onOptionsItemSelected(item);
          }
      
          private void addItemsToDataList(){
              dataList.add(new DrawerItem(getString(R.string.title_attendants), R.drawable.ic_action_attendants_list));
              dataList.add(new DrawerItem(getString(R.string.title_events), R.drawable.ic_action_events_list));
              dataList.add(new DrawerItem(getString(R.string.title_registration), R.drawable.ic_action_registration));
              dataList.add(new DrawerItem(getString(R.string.title_reports), R.drawable.ic_action_report));
              dataList.add(new DrawerItem(getString(R.string.title_settings), R.drawable.ic_action_settings));
          }
      }
       
    15. Add an image of yourself or any image and then go back to #3 above and change the HEADER_IMAGE value from 1 to the drawable representing the image that you added.

And with that we come to the conclusion of part 1 of the tutorial series on how to create and publish your first Android app. You should now be able to run your App and the NavigationDrawer should be working. It will will not navigate to anywhere yet, because we have not added it and we will do that in the next tutorial.

If you like this tutorial please share it with someone who can benefit from it or through your social media, If you want to be notified when I release the next tutorial in the series please use the opt-in form below to join my mailing list. If you need clarifications, use the comment button below to ask questions. If you have feedback for me on how I can improve my tutorials or what topic you want to learn more about, use the contact form to reach out to me.

<form action='//valokafor.us4.list-manage.com/subscribe/post?u=0600ce94a59d7720819aa3dd8&id=6e5492cf7d' class='frm' method='post'><input type='text' placeholder='Email Address' name='EMAIL' /><input type='text' placeholder='First Name' name='FNAME' /><input type='hidden' name='b_0600ce94a59d7720819aa3dd8_6e5492cf7d' value='' />
<input type='submit' value="Send Me New Tutorials">
</form>

The post Create and Publish Your First Android App – Part 1 appeared first on Val Okafor.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Val Okafor
Software Developer (Senior) ValOkafor.com
United States United States
My name is Val Okafor, I am a Senior Software Engineer with specialization in Android Development. Learning and problem solving is my passion and I share my Android development knowledge through my blog ValOkafor.com.

My Android courses are the courses I wish I had when I started. I teach Android development in the context of a fully developed Android app. I believe that new Android concepts are better understood if they are presented in the context of creating an app from scratch to finish.

I focus on creating Productivity Android apps and besides Android development I have 7 years’ experience as System Administrator supporting Enterprise applications and 2 years’ experience as a Web Developer building websites using PHP and ASP.Net.

I have worked for corporations such as The Home Depot, American Council on Exercise, Legend3D and HD Supply, Inc. I have a bachelor's degree in Information Technology from National University San Diego, California and a master's degree in Software Engineering from Regis University Denver, Colorado.

I enjoy sharing my extensive work experience through my blog, social media.

You may also be interested in...

Pro

Comments and Discussions

 
QuestionLost at step 3 Pin
gerrit.samson31-Aug-15 1:24
membergerrit.samson31-Aug-15 1:24 
QuestionIDE Pin
ssj28230-Jun-15 2:24
memberssj28230-Jun-15 2:24 
QuestionExcellent work - My Vote 5 Pin
Yildirim Kocdag12-Jun-15 0:31
memberYildirim Kocdag12-Jun-15 0:31 
GeneralMy vote of 5 Pin
Raul Iloc11-Jun-15 20:43
professionalRaul Iloc11-Jun-15 20:43 
QuestionBest Mobile Article of May 2015 Pin
Sibeesh Passion10-Jun-15 19:21
professionalSibeesh Passion10-Jun-15 19:21 
QuestionMissing files and code Pin
Rafael Fernandes Brasil10-Jun-15 13:33
memberRafael Fernandes Brasil10-Jun-15 13:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190518.1 | Last Updated 31 May 2015
Article Copyright 2015 by Val Okafor
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid