http://icyarena.com
http://icyarena.com
Welcome to Android world
Android app development
Creating First Application
  Posted by : Color Picker     Date : 23 February       Leave a comment
Let's start actual programming with Android Studio. Before you start writing your first example, you have to make sure that you have setup your Android development environment properly as explained in Android Environment Setup.
Create Android Application
It’s time. Let’s make your first project.
You’ll start simple. Many first programs are called “Hello World.” Let’s follow that tradition and then make a few small edits so that the app uses your name to greet you.
Creating a New Android Project
The first step in the application development process is to create a new project within the Android Studio environment. Begin, therefore, by launching Android Studio so that the “Welcome to Android Studio” screen appears as illustrated in Figure:
To create the new project, simply click on the Start a new Android Studio project option to display the first screen of the New Project wizard as shown in Figure:
Enter HelloWorld in Application name as shown above. Feel free to put your own name in the Company Domain textfield. As you type, you’ll notice the Package Name will automatically change to create a reverse domain style name based on your Application name and Company Domain.
Note:The Package Name is used to uniquely identify your app amongst other apps, that way any work an Android device has to be perform on behalf of the app always knows its source and can’t get confused between two apps.
You can set the Project location to any location on your hard drive – you do not need to follow the screenshot for that one.

Click Next at the bottom of the window to progress to the next part of the project setup.
The screen is where you select device types and operating systems to target. For your first app, you’ll use the default – API 15, which is Android 4.0.3 (ICS). Every app will have different requirements and you may want to choose something else, depending on the situation.
The percentage reflects what percentage of devices currently run that version of Android.

Since the project is not intended for Google TV, Google Glass or wearable devices, leave the remaining options disabled before clicking Next.
Creating an Activity
A range of different activity types is available when developing Android applications.For the purposes of this example, however, simply select the option to create a Blank Activity.
Click Next button to continue.
you are at the final screen before you dig into some actual coding. To speed this part up a little bit you will use the pre-populated default values, but what is actually done with these values?

  • Activity Name: Once the project setup is complete, you will see a java class with this name i.e. this is the name you will use to refer to your Activity inside your code.
  • Layout Name: You’re going to define your Activity in Java, but the layout of everything it will show to the user is defined in a special sort of Android XML.
If you follow above screenshot, this will create a java file HomeActivity.java(containing java class) and a XML file home.xml(containing layout).

Click Finish. Android Studio takes this as its cue to go do a bunch of behind-the-scenes operations and create your project.
After a brief moment, Android Studio will finish building your project. The project is pretty empty, of course, but it still has everything it needs already set up so that it can be launched on an Android device or emulator.
You can anytime change Design view to Text view of home.xml file.
Before you get into any programming, let’s talk about how you’re going to get this app running. It’s time to say “Hello world!”.
Running on an Emulator or Android Virtual Device(AVD)
You’ve got Android Studio and you’ve created an app. So how do you run it? If you have a physical Android device available, you’ll learn how to use that soon. But for those without one, you also have the choice to run your App on an emulator.

Click AVD Manager.It’s the button in the toolbar with a purple display.
Click on Create Virtual Device
For now you just want to emulate a phone sized device but if you wanted to emulate an Android Wear watch or an Android TV then you have options to do so here.
Select Nexus S in the list of devices available to you and click Next.

Select Lollipop and make sure the one selected has the value x86 in the ABI column. We want the emulator to be running as fast as possible on our x86 computers
Click Next once this is done to move to the final screen. The last screen is simply a confirmation of your previous choices with the option to configure some other properties of your device such as device name, startup orientation, and RAM size.For now leave these set as their defaults or set as my setting and click Finish
You’ve just created a fresh virtual device ready for use to test out your new app.Now, close the AVD Manager to go back to Android Studio’s main view. Now that you’ve configured everything, there’s but one step left…

Click the Run button. It looks like a “play” icon.
A new window will appear, asking you to choose the device you wish to test your App on. You currently have no devices running, so lets start the AVD you just created. Ensure the Launch Emulator radio button is checked and your AVD is selected in the drop down menu, then click OK.
Note: You may have to wait a while as the emulator loads, and you may even need to try it more than once for the emulator to get it right, but once it’s ready, you should see something like this:(You need to unlock the phone by up swipe the unlock key)
Congratulations! You made your first Android app!
Modifying the Example App and Putting a Personal Stamp on Your App
You’ve made your first App, but what’s the first thing you always want to put on any of your work? Thats right, your name!
Before that you need to know about Android Project Structure.

Android Project Structure:
  1. Java: It’s the job of your Java code to get things done.
  2. Resources: It’s not enough to just get the job done. It needs to be done in style. Your App is never going to stand out unless it has great icons and images, well-designed layouts, engaging copy text, and maybe even some smooth animations.

    Initially, the app/res (Resources) folder contains:
      Drawable folders that hold images — just the default launch icon for now.
      The layout folder with XML that represents the screen designs.
      The menu folder with XML of the items that will appear on the Action Bar. More on that later.
      The values folder with XML containing dimensions, strings, and styles.
  3. AndroidManifest.xml: This XML file informs your system of the app’s hardware and software requirements and contains your app’s name, icon, and version.
  4. Intent: Want to show the user a screen? Want to navigate to a website? Whatever the job is, in Android it is going to take the form of an Intent
Putting a Personal Stamp on Your App
Navigate to res/values/strings.xml and double-click the file. When you open the file, you’ll see three string resources in XML.

Change the hello_world string. That string is the one that the app displays on the screen. So, change it to something more personal that incorporates your own name – something like:
<string name="hello_world">Color Picker is learning android app making</string>
Click Run. When the App launches again, you’ll see your personalized message!
Adding a component:
In the Palette panel, locate the Widgets category. Click and drag the Button object and drop it in the center of the user interface design when the green marker lines appear to indicate the center of the display:
The next step is to change the text that is currently displayed by the Button component. Double click on the object in the design layout to display the text and id editing panel as illustrated in Figure.
Within the panel, change the text property from “New Button” to “Click Me !” and set id "button1".
Now we should give an id to TextView component.Click on the TextView component,when selected double click on it and set id textview1.
Accessing Views From Within Java for making button functional
Switch to Text View from Design View of home.xml.

There’s also a change to make in the text tag. The name of the string resource hello_world is a bit outdated now, don’t you think?
Right-click on the @string/hello_world part of the line and then choose Refactor > Rename.
Then, type SimpleText and click Refactor.
This not only changes the name of the resource ID in your layout file, it also changes the original resource ID in your strings.xml file. It also renames the resource ID wherever else it might be used in the project.
This is a useful trick to remember when renaming something that appears all over your project!

Now open HomeActivity.java.
Define two variables(mytext and mybutton) within HomeActivity class.
TextView mytext;
Button mybutton;
The TextView class hasn’t been imported into HomeActivity.java yet. Android Studio can quickly auto-import files for you. Just click on TextView and tap Option-Enter(alt+Enter) on your keyboard to automatically import TextView.Similarly import button class.
Add these lines at the end of onCreate function.
// Access the TextView having id "textview1" defined in layout XML
mytext = (TextView) findViewById(R.id.textview1);
// Access the Button having id "button1" defined in layout XML
mybutton = (Button) findViewById(R.id.button1);
// listen for it while clicking
mybutton.setOnClickListener(this);
Android Studio is smart and can help you do the implementation. Simply single-click on 'this', which is underlined in red, indicating an issue. Then, when a yellow light bulb appears at the beginning of the line, click on it and select Make ‘HomeActivity’ implement ‘android.view.View.OnClickListener’.
Simply click OK on the next dialog, which lets you know which method(s) Studio will automatically create for you.
Studio then generates the code necessary to make your MainActivity qualify as a union-certified OnClickListener.
First, Android Studio added a bit to the class declaration indicating that the Activity implements a specific interface:
public class HomeActivity extends Activity implements View.OnClickListener

Second, Studio added a stub for a method you need to implement in order to get your OnClickListener license: onClick. This method fires when your Button gets pressed.
The method (onClick) currently does nothing. So add the following code to onClick to make it do something:
mytext.setText("Button pressed!");// Change text field when click
Can you tell from the code what should happen?
Run your app and see if you’re right…
The app now changes the text in the TextView when you press the Button. Cool! You’ll be putting this Button to even better use later to submit input text
Involving the Keyboard
Now it’s time to get some user input… by introducing an EditText. This is a special subclass of TextView that opens the keyboard and displays what the user types as its content.

Add the EditText XML to home.xml as a sibling to the TextView.
<EditText
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:layout_marginTop="40dp"
	android:layout_marginLeft="0dp"
	android:id="@+id/edittext1"
	android:hint="@string/hint"/>
Notice the special attribute, hint. You’re using this text as a placeholder in the input field. The app will overwrite it once the user starts typing.
As usual, you need to define the string resource for your hint in res/values/strings.xml:
<string name="hint">Tap me and write something</string>
Now open MainActivity.java and add a new variable for the EditText (below the other two existing variables):
EditText myedittext;
As before, remember to use Option-Enter to automatically add the missing imports.

Next, add the following code to the end of onCreate:
// Access the EditText defined in layout XML
myedittext = (EditText) findViewById(R.id.edittext1);
The above code, similar to the previous code, simply gets a reference to the EditText control and saves it in the assigned variable.

Now that you have a reference to the EditText control, you need to do something with user input.Open HomeActivity and Replace the current contents of onClick method with the following:
// Take what was typed into the EditText and use in TextView
mytext.setText("Color Picker is typing: " + myedittext.getText().toString());
Run your app, and try typing a few things!
Now you receive user input with an EditText, submit it with a Button, and display it in a TextView. Very nice!
Display Toast Welcoming:
Every time when you run this app. it will welcome you.
Open MainActivity.java and add following codes at the end of onCreate method.Don't forget to import class by clicking on Toast and pressing alt+Enter.
Toast.makeText(this, "Welcome !", Toast.LENGTH_LONG).show();
Remembering Your Name to Welcome you
Everything you’ve done so far with regard to user input only persists while the app is running. But what about between sessions? Let’s see some data persistence in action, with a new feature that will record and remember your name each time you open the app.
There are a few good options on Android to persist data, and the simplest one is SharedPreferences.
SharedPreferences stores data in key=value pairs, meaning that you specify a name (the key) for a piece of data (the value) when you save it, and you can retrieve it later by using the original key.

First, add the following constants and variable to HomeActivity.java (to the same place as the previous variables):
//Declare a variable named "mysession" for storing a reference to the sharedpreferences class.
SharedPreferences mysession;
//File name for storing data
private static final String Pref_File_Name = "SessionData";
//key to store value
private static final String Name_of_Key = "username";
You’ll use SessionData as a filename to keep your SharedPreferences in a single location. You’ll use Name_of_Key as the key for storing your name in shared preferences.
Now Replace this line :
Toast.makeText(this, "Welcome !", Toast.LENGTH_LONG).show();
with:
// Access the device's key-value storage
mysession = getSharedPreferences(Pref_File_Name, MODE_PRIVATE);
// Read the user's name,or an empty string if nothing found
String name = mysession.getString(Name_of_Key, "");
// If the name is valid, display a Toast welcoming.
if (name.length() > 0) { 
	Toast.makeText(this, "Welcome back, " + name + "!", Toast.LENGTH_LONG).show();
}else{
	/*Displaying the Name Dialog*/	
}
The first thing you do is access SharedPreferences, with MODE_PRIVATE meaning that only your HelloWorld app can access the data stored here. This means that your saved data will not get overwritten by another application which might have used the same key as you.

Then you simply ask the preferences object for whatever value is stored using the key Name_of_Key. The second parameter for the method can be used to set a default value to be returned in case there is no value stored using the key you provide. So, you use an empty String as the default value here.

Finally, you check to see if the retrieved String actually has any content, and display a message if so. Your message takes the form of a Toast, which is a short-lived pop-up message that appears for a bit and then fades away.Easy!
Displaying the Name Dialog
Dialogs are small windows that alert the user. They may contain ways for the user to provide input or make choices. You’re going to use an AlertDialog, specifically.
Replace "/*Displaying the Name Dialog*/" i.e add this lines within else condition.
//show a dialog to ask for their name
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Hello!");
alert.setMessage("What is your name?");
// Create EditText for entry
final EditText input = new EditText(this);
alert.setView(input);
// Make an "OK" button to save the name
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	public void onClick(DialogInterface dialog, int whichButton) {
		// Grab the EditText's input
		String inputName = input.getText().toString();
		// Put it into memory (don't forget to commit!)
		SharedPreferences.Editor e = mysession.edit();
		e.putString(Name_of_Key,inputName);
		e.commit();
		// Welcome the new user
		Toast.makeText(getApplicationContext(), "Welcome, " + inputName + "!", Toast.LENGTH_LONG).show();
	}
});
// Make a "Cancel" button that simply dismisses the alert
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
	public void onClick(DialogInterface dialog, int whichButton) {}
});
alert.show();
The app will reach this else condition when there is no valid name saved using the Name_of_Key, key. You use an AlertDialog.Builder to give your AlertDialog a title, a message, and an EditText in the center for the user to type in their name.

Then, you add two buttons to the AlertDialog: a positive and a negative button. The first thing you define for each is the text displayed on the button – “OK” and “Cancel” are pretty standard choices. The second thing you define for each button is an OnClickListener.
Run your app and check out your Dialog.
Type in your name, press OK and see the Toast greeting. From now on, your app will remember your name and greet you each time you launch it!
Configuring the Launcher Icon
Now, we will change the default Android icon. Download android_blue_icon.png and then right click on the file, choose copy and paste on app/res/drawable directory by right click on drawable folder of Android Studio to add them to your project.Press OK if any window appears.
Open AndroidManifest.xml.Find the opening application tag and change the icon attribute value "@mipmap/ic_launcher" to "@drawable/android_blue_icon".
Oh!.......Enough for today !!!
If you don't understand anything please feel free to comment.You can download all Files if you need.At the end of this tutorial you will get Download Button

Complete Example Code

  • AndroidManifest.xml
  • home.xml
  • strings.xml
  • File: app / manifests / AndroidManifest.xmlText View
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.icyarena.helloworldapp" >
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/android_blue_icon"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".HomeActivity"
                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>
    File: app / res / layout / home.xmlText View
    <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=".HomeActivity">
    
        <TextView android:text="@string/SmpleText" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textview1" />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:layout_marginLeft="0dp"
            android:id="@+id/edittext1"
            android:hint="@string/hint"/>
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Click Me !"
            android:id="@+id/button1"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />
    
    </RelativeLayout>
    File: app / res / values / strings.xmlText View
    <resources>
        <string name="app_name">HelloWord</string>
        <string name="SimpleText">Color Picker is learning android app making</string>
        <string name="hint">Tap me and write something</string>
        <string name="action_settings">Settings</string>
    </resources>
  • home.xml
  • File: app / res / layout / home.xmlDesign View
    Screenshot: home.xml
  • HomeActivity.java
  • File: app / java / HomeActivity.javaText View
    package com.icyarena.helloworldapp;
    
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.SharedPreferences;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    
    public class HomeActivity extends ActionBarActivity implements View.OnClickListener {
        /*
        Declare all variable so that it can be used all over the HomeActivity class
        */
        TextView mytext;
        Button mybutton;
        EditText myedittext;
        //Declare a variable named "mysession" for storing a reference to the sharedpreferences class.
        SharedPreferences mysession;
        //File name for storing data
        private static final String Pref_File_Name = "SessionData";
        //key to store value
        private static final String Name_of_Key = "username";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.home);
            /*
            all codes go here for functioning all components of home.xml
            */
            // Access the TextView having id "textview1" defined in layout XML
            mytext = (TextView) findViewById(R.id.textview1);
            // Access the Button having id "button1" defined in layout XML
            mybutton = (Button) findViewById(R.id.button1);
            // Access the EditText defined in layout XML
            myedittext = (EditText) findViewById(R.id.edittext1);
            // listen for it while clicking
            mybutton.setOnClickListener(this);
            //welcome message
            // Access the device's key-value storage
            mysession = getSharedPreferences(Pref_File_Name, MODE_PRIVATE);
            // Read the user's name,or an empty string if nothing found
            String name = mysession.getString(Name_of_Key, "");
            // If the name is valid, display a Toast welcoming.
            if (name.length() > 0) {
                Toast.makeText(this, "Welcome back, " + name + "!", Toast.LENGTH_LONG).show();
            }else{
                //show a dialog to ask for their name
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setTitle("Hello!");
                alert.setMessage("What is your name?");
                // Create EditText for entry
                final EditText input = new EditText(this);
                alert.setView(input);
                // Make an "OK" button to save the name
                alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Grab the EditText's input
                        String inputName = input.getText().toString();
                        // Put it into memory (don't forget to commit!)
                        SharedPreferences.Editor e = mysession.edit();
                        e.putString(Name_of_Key,inputName);
                        e.commit();
                        // Welcome the new user
                        Toast.makeText(getApplicationContext(), "Welcome, " + inputName + "!", Toast.LENGTH_LONG).show();
                    }
                });
                // Make a "Cancel" button that simply dismisses the alert
                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {}
                });
                alert.show();
            }
        }
    
    
        @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_home, 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);
        }
    
        @Override
        public void onClick(View v) {
            // Take what was typed into the EditText and use in TextView
            mytext.setText("Color Picker is typing: " + myedittext.getText().toString());
        }
    }
    Comments (14) Leave a comment
    Raji   2:38 am , 30 Oct 17  
    can you please tell me how to save and retrieve in hindi language in android?
    Reply
    Raji   2:37 am , 30 Oct 17  
    can you please tell me how to save and retrieve in hindi language in android?
    Reply
    Amit Kumar Pandya   2:29 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Amit Kumar Pandya   2:28 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Amit Kumar Pandya   2:28 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Amit Kumar Pandya   2:28 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Amit Kumar Pandya   2:28 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Amit Kumar Pandya   2:28 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Amit Kumar Pandya   2:28 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Amit Kumar Pandya   2:28 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Amit Kumar Pandya   2:28 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Amit Kumar Pandya   2:28 am , 17 May 17  
    its very good example for sqlite DB i've got. but the list is not updating after i click on the save button from storecontact.java file. please help me out for this problem. i have searched for the solutions and tried also but they are not working.
    Reply
    Halmiton Tim   7:17 pm , 30 Apr 17  
    Why my application is stopped working ?
    Reply
    Halmiton Tim   7:17 pm , 30 Apr 17  
    Why my application is stopped working ?
    Reply
    Submit your comment
    Name * Email * Your comment * Please prove you are not a spambot *   What is 4+9 ?