Android Tutorial

Android, an open source operating system for mobile devices (Smartphone and tablet), led by Google. The Android SDK provides a set of tools and APIs to develop Android applications, using Java. So, if you know Java, Android programming is easy :)
In this series of tutorials, we show you the list of basic tutorials to get you start program Android easily.
Note
All Android tutorials are developed in Eclipse 3.7, and tested with Android 2.3.3.
All Android tutorials are developed in Eclipse 3.7, and tested with Android 2.3.3.
P.S This is just the initial version of Android tutorials, will keep publishing more in future.
1. Quick Start
Get you start in Android programming.
- Android hello world example
Tools and SDK to develop Android applications.
2. Fundamentals
Some Android basic stuffs.
- Android activity example
Understand Android’s activity, a simple example to navigate from one screen (activity) to another screen (activity). - Android wrap_content and fill_parent example
The different between wrap_content and fill_parent to control the component’s width and height. - Attach Android source code to Eclipse IDE
Android source code is important to understand how Android works, a guide to attach Android’s source code to Eclipse IDE.
3. User Interface Controls
Play with Android UI controls.
- Android button example
Use “Button” to display a simple button. - Android textbox example
Use “EditText” to render an editable textbox component. - Android password example
Use “EditText” + inputType=”textPassword” to render a password component. - Android checkbox example
Use “CheckBox” to render the checkbox component. - Android radio buttons example
Use “RadioButton” and “RadioGroup” to render radio button component in the group. - Android toggle button example
Use “ToggleButton” to render a button which has only two states (On and Off). - Android rating bar example
Use “RatingBar” to render a rating bar in stars icon. - Android spinner (drop down list) example
Use “Spinner” to render a drop down box for selecting items. - Android date picker example
Use “DatePicker” and “DatePickerDialog” to render a date picker component. - Android time picker example
Use “TimePicker” and “TimePickerDialog” to render a time picker component. - Android analogclock and digitalclock example
Use “AnalogClock” and “DigitalClock” to render a clock like component, which supports hours, minutes and seconds. - Android progress bar example
Use “ProgressDialog” to display a progress bar in dialog to tell us that your task takes time to finish. - Android alert dialog example
How to display an alert box. - Android prompt dialog example
Custom AlertDialog example. - Android custom dialog example
Custom Dialog example. - Android Toast example
Custom Toast view example. - Android ImageView example
Use “ImageView” to display an image file. - Android ImageButton example
Use “ImageButton” to display a button with a customized background image. - Android ImageButton selector example
Use “Button” and “selector” tag to display buttons’ images depend on the button states.
4. Layouts
Play with Android layout controls.
- Android LinearLayout example
Most common layouts, arranges components in horizontal or vertical order. - Android RelativeLayout example
Most flexible layouts, arranges components based on the “relative” or sibling component. - Android TableLayout example
Most flexible layout, arranges components in row and column format, just like HTML table , <tr> and <td>. - Android ListView example
Display components in a vertical scrollable list. - Android GridView example
Display componenets in a two-dimensional scrolling grid. - Android WebView example
Allow you to open an own windows for viewing URL or custom html markup page.
5. FAQs
Some common asked questions in Android.
- How to open an URL in Android’s web browser
- How to set default activity for Android application
- How to make a phone call in Android
- Where to download Samsung Galaxy S2 USB driver?
- Android debugging on real device
- Android – How to center button on screen
- How to turn on/off camera LED/flashlight in Android
- Android : how to check if device has camera
- How to send SMS message in Android
- How to send Email in Android
- Android : The connection to adb is down, and a severe error has occurred.

Hi
the application xxx has stopped unexpectedly please try again
what is solution of the android pro………..
hello ,sir can you help me to create a photo albums and how i can add albums to classify photo !!!! :)
Sir, your tutorials are very helpfull for me.
but i need a tutorial on framents.
can you please give the tutorial on fragments
It is great tutorial, thanks sir for Support.
sir,i want to take some string data from user and process them in database using php and mysql no sqlite and return the result to the application……pls help me ..i am new to android…..
Really helpful.Thank you very much .
hi,
i’m very glad to see this link. i have already get enough idea on spring-jsf from your site,now time for android.
Thanks for your excellent support
Great tutorial I am new in android and its vary help full ……
Thanks
sir I need a help regarding
I want to display multiple(4) buttons randomly on screen
every button created in java file extend views
plllllllzzzzzzzzzzzzzz help
hi guys i want to know how to comvert a program to .apk file,
and even i tried these steps -> project_name -> bin -> .apk file….. but its not working..
and even i tried export to android project then also im getting error like “failed because of parsing in package” so anyone help me out of this
Im a follower of your website and its really useful for me till now. I have a doubt, as like IF I WANT AN OVERLAY IN MY ANDROID APP ON ALL ACTIVITIES, what should i do, will be helpful if u make an example
I found your blog pretty cool, keep posting these kind of articles. You really helped me, i have a good start with android, thanks a ton.
great tutorials, direct and to the point
please post more
when will other tutorial for android will be posted?? I am waiting for next tutorial desperately
great tutors broda, im wait and still follow for next
Hi Mkyong i m making a project in mobile tracking with android application n data of that would sent to php server . Can u plzzzzzzz help me in my project by providing source code it’s very urgent. Any type of help would be a great boon.. . Continue with ur good works bye……………….
SKobu I may try to help you.Please drop in your email.
Nice tutorial to get started…!
Hello Sir , these are very good tutorials and are in understandable way..thank u very much for that.
I have a query to ask you. I donot know its a small task or big task .but Suppose i have 20 lines of a text. In that when i click on some word it should popup an alert..
For instance lets take some text
“When I had a financial setback in the early 1990s, I saw it
more as an “ABBERATION ” from the norm than as a final sentence. I
knew what it was like to be whole, and all I had to do was get
back to that place.”
In the text when i click or touched the word ABBERATION (quoted and capitalized ) in above text it should give me a pop-up with my own text ( i’ll write while coding)
I know one way is writing the text in set message method (alert.setMessage (“”)) but i donot want to write for each word in the text..can you please tell me the way to solve this problem..
I have one more que to as but not now..
Thankyou and love to here back with your reply…Have a Great Day :-)
Hi,
This is possible through
.
Check this out:
http://developer.android.com/reference/android/text/Spannable.html
http://stackoverflow.com/questions/7338697/android-development-how-to-replace-part-of-an-edittext-with-a-spannable
Hello sir, i’m making an android app. which is totally in “hindi(language)”, in which i need, hindi fonts,hindi onscreen keyboard in emulator, i need help, how i use hindi fonts and how i add hindi onscreen keyboard in emulator
package grimbo.android.demo.slidingmenu;
import grimbo.android.demo.slidingmenu.MyHorizontalScrollView.SizeCallback;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
/**
* This demo uses a custom HorizontalScrollView that ignores touch events, and
* therefore does NOT allow manual scrolling.
*
* The only scrolling allowed is scrolling in code triggered by the menu button.
*
* When the button is pressed, both the menu and the app will scroll. So the
* menu isn’t revealed from beneath the app, it adjoins the app and moves with
* the app.
*/
public class HorzScrollWithListMenu extends Activity
{
final String KEY_TAG = “weatherdata”; // parent node
final String KEY_ID = “id”;
final String KEY_CITY = “city”;
final String KEY_TEMP_C = “tempc”;
final String KEY_TEMP_F = “tempf”;
final String KEY_CONDN = “condition”;
final String KEY_SPEED = “windspeed”;
final String KEY_ICON = “icon”;
// List items
ListView list;
BinderData adapter = null;
List<HashMap> weatherDataCollection;
MyHorizontalScrollView scrollView;
View menu, demo,profile;
View app;
ImageView btnSlide;
boolean menuOut = false;
Handler handler = new Handler();
int btnWidth;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final LayoutInflater inflater = LayoutInflater.from(this);
scrollView = (MyHorizontalScrollView) inflater.inflate(
R.layout.horz_scroll_with_list_menu, null);
setContentView(scrollView);
menu = inflater.inflate(R.layout.horz_scroll_menu, null);
// ///demo= inflater.inflate(R.layout.demo, null);
app = inflater.inflate(R.layout.horz_scroll_app, null);
ViewGroup tabBar = (ViewGroup) app.findViewById(R.id.tabBar);
btnSlide = (ImageView) tabBar.findViewById(R.id.BtnSlide);
btnSlide.setOnClickListener(new ClickListenerForScrolling(scrollView,
menu));
final View[] children = new View[] { menu, app };
// Scroll to app (view[1]) when layout finished.
final int scrollToViewIdx = 1;
scrollView.initViews(children, scrollToViewIdx,
new SizeCallbackForMenu(btnSlide));
Button logout=(Button)findViewById(R.id.Button08);
Button profile=(Button)findViewById(R.id.Button4);
Button profile1=(Button)findViewById(R.id.Button01);
Button follower=(Button)findViewById(R.id.Button04);
Button following=(Button)findViewById(R.id.Button02);
profile.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i= new Intent(HorzScrollWithListMenu.this,Themes.class);
startActivity(i);
}
});
following.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
WebService_oGoingfollowing();
}
private void WebService_oGoingfollowing() {
// TODO Auto-generated method stub
String name;
JSONArray c = null;
// Live
//static String urlmain = “http://api.ogoing.com/”;
// Mobile QA
String urlmain = “http://ogoingritts.rigelnetworks.com/”;
String inputPortalName = “http://ogoingqa.rigelnetworks.com”;
String inputUserName = “chiragmankani”;
String inputPassword = “123@chiragG”;
String ID = “4776″;
String deviceid = “3bf19e537d8dedb6ec2e6b461945c8638e54a4871caba10c8b485ebc3bab5691″;
String portal = “http://ogoingqa.rigelnetworks.com”;
// TODO Auto-generated method stub
//private static final String URL = “http://api.ogoing.com/user.asmx?op=ValidUser”;
final String URL = urlmain+”UserProfile.asmx?op=GetFollowingOfUsers”;
final String SOAP_ACTION_NEW = “http://www.ogoingapi.com/GetFollowingOfUsers”;
/**
* Getting Contact information
*
* @param attendeeCredentials
* @param inSeqNum
* @return GetAttendeesContactInfoResponse
*/
/// JSONObject callWebServiceJson(String UserName, String Password,String PortalName, String DeviceId) {
JSONObject jsonObj = null;
String ValidLogin=”"
+”"
+”"
+”"
+”"+inputUserName+”"
+”"+inputPassword+”"
+”"+portal+”"
+”"+ID+”"
+”"+0+”"
+”"+”getall”+”"
+”"
+”"
+”";
DefaultHttpClient httpClient = new DefaultHttpClient();
String envoloper = String.format(ValidLogin);
// request parameters
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 15000);
// set parameter
HttpProtocolParams.setUseExpectContinue(httpClient.getParams(),true);
// POST the envelope
HttpPost httppost = new HttpPost(URL);
// add headers
// Set Method Action
httppost.setHeader(“soapaction”, SOAP_ACTION_NEW);
httppost.setHeader(“Content-Type”, “text/xml; charset=utf-8″);
String response = “”;
try
{
// the entity holds the request
HttpEntity entity = new StringEntity(envoloper);
httppost.setEntity(entity);
// Response Handler
ResponseHandler responseHandler = new ResponseHandler()
{
@Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
// get response entity
HttpEntity entity = response.getEntity();
// read the response as byte array
StringBuffer out = new StringBuffer();
byte[] b = EntityUtils.toByteArray(entity);
// write the response byte array to a string buffer
out.append(new String(b, 0, b.length));
return out.toString();
}
};
// Getting the response
response = httpClient.execute(httppost, responseHandler);
// Sending the Response to parsing class
String stt[] = response.split(“”);
String stt2[] = stt[1].split(“”);
Log.i(“”, “stt” + stt);
Log.i(“”, “stt2″ + stt2);
String my_string = stt2[0];
Spanned abc = Html.fromHtml(Html.fromHtml(my_string).toString());
String my_final_string = abc.toString();
// jsonObj = new JSONObject(my_final_string);
// DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
//Document doc = docBuilder.parse (getAssets().open(“weatherdata.xml”));
weatherDataCollection = new ArrayList<HashMap>();
// normalize text representation
//doc.getDocumentElement ().normalize ();
// NodeList weatherList = doc.getElementsByTagName(“weatherdata”);
HashMap map = null;
JSONArray jarray = new JSONArray(my_final_string);
for (int i = 0; i < jarray.length(); i++) {
//for (int i = 0; i < weatherList.getLength(); i++) {
map = new HashMap();
//// Node firstWeatherNode = weatherList.item(i);
JSONObject menuObject = jarray.getJSONObject(i);
String uname1 = menuObject.getString(“UserName”);
String image = menuObject.getString(“ImageURL”);
map.put(KEY_CITY, (uname1));
map.put(KEY_ICON, (image));
weatherDataCollection.add(map);
}
followerBinderData bindingData = new followerBinderData(HorzScrollWithListMenu.this,weatherDataCollection);
list = (ListView)app.findViewById(R.id.list);
Log.i(“BEFORE”, “<>”);
list.setAdapter(bindingData);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Intent i = new Intent(HorzScrollWithListMenu.this, Followerprofile.class);
i.putExtra(“Username”, weatherDataCollection.get(position).get(KEY_CITY));
// start the sample activity
startActivity(i);
}
});
}
catch (Exception exc) {
exc.printStackTrace();
}
}
});
follower.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
WebService_oGoingfollower();
}
private void WebService_oGoingfollower() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
String name;
JSONArray c = null;
// Live
//static String urlmain = “http://api.ogoing.com/”;
// Mobile QA
String urlmain = “http://ogoingritts.rigelnetworks.com/”;
String inputPortalName = “http://ogoingqa.rigelnetworks.com”;
String inputUserName = “chiragmankani”;
String inputPassword = “123@chiragG”;
String ID = “4776″;
String deviceid = “3bf19e537d8dedb6ec2e6b461945c8638e54a4871caba10c8b485ebc3bab5691″;
String portal = “http://ogoingqa.rigelnetworks.com”;
// TODO Auto-generated method stub
//private static final String URL = “http://api.ogoing.com/user.asmx?op=ValidUser”;
final String URL = urlmain+”UserProfile.asmx?op=GetFollowersOfUsers”;
final String SOAP_ACTION_NEW = “http://www.ogoingapi.com/GetFollowersOfUsers”;
/**
* Getting Contact information
*
* @param attendeeCredentials
* @param inSeqNum
* @return GetAttendeesContactInfoResponse
*/
/// JSONObject callWebServiceJson(String UserName, String Password,String PortalName, String DeviceId) {
JSONObject jsonObj = null;
/* String ValidLogin=”"+
“”
+ “”+”"
+”"+portal+”"
+”"
+”"
+”";*/
String ValidLogin=”"+
“”
+”"+
“”
+”"+inputUserName+”"
+”"+inputPassword+”"
+”"+portal+”"
+”"+ID+”"
+”"+0+”"
+”"+”getall”+”"
+”"
+”"
+”";
DefaultHttpClient httpClient = new DefaultHttpClient();
String envoloper = String.format(ValidLogin);
// request parameters
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 15000);
// set parameter
HttpProtocolParams.setUseExpectContinue(httpClient.getParams(),true);
// POST the envelope
HttpPost httppost = new HttpPost(URL);
// add headers
// Set Method Action
httppost.setHeader(“soapaction”, SOAP_ACTION_NEW);
httppost.setHeader(“Content-Type”, “text/xml; charset=utf-8″);
String response = “”;
try
{
// the entity holds the request
HttpEntity entity = new StringEntity(envoloper);
httppost.setEntity(entity);
// Response Handler
ResponseHandler responseHandler = new ResponseHandler()
{
@Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
// get response entity
HttpEntity entity = response.getEntity();
// read the response as byte array
StringBuffer out = new StringBuffer();
byte[] b = EntityUtils.toByteArray(entity);
// write the response byte array to a string buffer
out.append(new String(b, 0, b.length));
return out.toString();
}
};
// Getting the response
response = httpClient.execute(httppost, responseHandler);
// Sending the Response to parsing class
String stt[] = response.split(“”);
String stt2[] = stt[1].split(“”);
Log.i(“”, “stt” + stt);
Log.i(“”, “stt2″ + stt2);
String my_string = stt2[0];
Spanned abc = Html.fromHtml(Html.fromHtml(my_string).toString());
String my_final_string = abc.toString();
// jsonObj = new JSONObject(my_final_string);
// DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
//Document doc = docBuilder.parse (getAssets().open(“weatherdata.xml”));
weatherDataCollection = new ArrayList<HashMap>();
// normalize text representation
//doc.getDocumentElement ().normalize ();
// NodeList weatherList = doc.getElementsByTagName(“weatherdata”);
HashMap map = null;
JSONArray jarray = new JSONArray(my_final_string);
for (int i = 0; i < jarray.length(); i++) {
//for (int i = 0; i < weatherList.getLength(); i++) {
map = new HashMap();
//// Node firstWeatherNode = weatherList.item(i);
JSONObject menuObject = jarray.getJSONObject(i);
String uname1 = menuObject.getString(“UserName”);
String image = menuObject.getString(“ImageURL”);
map.put(KEY_CITY, (uname1));
map.put(KEY_ICON, (image));
weatherDataCollection.add(map);
}
followerBinderData bindingData = new followerBinderData(HorzScrollWithListMenu.this,weatherDataCollection);
list = (ListView)app.findViewById(R.id.list);
Log.i(“BEFORE”, “<>”);
list.setAdapter(bindingData);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Intent i = new Intent(HorzScrollWithListMenu.this, Followerprofile.class);
i.putExtra(“Username”, weatherDataCollection.get(position).get(KEY_CITY));
// start the sample activity
startActivity(i);
}
});
}
catch (Exception exc) {
exc.printStackTrace();
}
}
});
logout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(HorzScrollWithListMenu.this,LoginActivity.class);
startActivity(i);
finish();
}
});
I’m really enjoying the theme/design of your site. Do you ever run into any browser compatibility problems? A handful of my blog audience have complained about my blog not working correctly in Explorer but looks great in Safari. Do you have any solutions to help fix this issue?
send and receive data from local machine via JSP web service in android
hi could u give me sample code for remote service in android with clear explanation
very less topics
like adapters , fragments and so on are missing ….. keep trying to add these things as well
more over i really appreciate ur efforts
Hi,
Your site is wonderful. It will surely help upcoming android programmers. Is it possible for you to write some articles for sensors which are present inside android device? If you can write some samples will be helpful.
Kind regards,
Vishal Kulkarni
Please help me how can we upload a file from Andriod to FTP Server (Source code).
Sir,how to store the android apps data,stored to cloud(Eucalyptus cloud).
hello sir….Could u tell me how to send data to server with example….
You need to learn web services to know how to save your data in database or any external server.
Hello sir its very interesting to learn android from your tutorials and its great experience to learn android through your tutorials thank you sir
Hi Sir,
Please upload android XML parsing with good example and description.
I wait for your response…
Really Great Tutorial… Thank you so much Mr.Mkyong…
hi could u tel me how to download a file in android using service class with example plzzzzzz
hi could u tel me how to download a file in android using service with example code plzzzzzzzzzzzzzzz
Hi.These are very useful for us.Thanks for tutorial.I want to ask question with your permission.I’m studying android application that it’s need android device connect to Mssql Server without web services.How can ? do it.I wait your responds.
I want to know 1.how will be store and connect backend
2. how to link .xml and .java files please help me
it is a gate way of develop android application. it is very useful for beginner
Thanks for the tutorials. Very easy to follow and learn step by step. Make me feel more confident after each tutorial. Nice!
Thank You for the tutorial..It’s Really helpful for those who wants to get started with android apps.Once again Thank you So much Mr. Yong
it is nice tutorial to get started thank you :-)
Sir U want the cod about the sqlite connection and all other required information because u are giving very easy