Android Tutorial

android-logo

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.

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.

2. Fundamentals

Some Android basic stuffs.

3. User Interface Controls

Play with Android UI controls.

4. Layouts

Play with Android layout controls.

5. FAQs

Some common asked questions in Android.

References

  1. Android Developer
  2. Android Fundamental
  3. Android in Wikipedia

278 comments on “Android Tutorial

  1. i am very beginner in android. your tutorial is very helpful for me. now, i need some tutorial on current location automatically store in database using SQlite. Please give me some tutorial.

  2. private void ApiCall() {
    String url = Common.ROOMS;
    Uri.Builder builder = Uri.parse(url).buildUpon();
    builder.appendQueryParameter(“user_id”, userId);
    builder.appendQueryParameter(“key”, key);

    String apiurl = builder.build().toString();
    StringRequest strRequest = new StringRequest(Request.Method.GET, apiurl,
    new Response.Listener() {
    @Override
    public void onResponse(String response) {
    try {

    JSONObject jsonObject = new JSONObject(response);
    if (jsonObject.getString(“status”).equals(“1”)) {
    if (roomModelList.size() > 0) {
    roomModelList.clear();
    }
    JSONObject jsonObject1 = jsonObject.getJSONObject(“data”);
    JSONArray jsonArray = jsonObject1.getJSONArray(“floors”);
    for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject2 = jsonArray.getJSONObject(i);
    JSONArray jsonArray1 = jsonObject2.getJSONArray("rooms");
    for (int j = 0; j < jsonArray1.length(); j++) {
    JSONObject jsonObject3 = jsonArray1.getJSONObject(j);
    RoomModel roomModel = new RoomModel();
    roomModel.setRoomId(jsonObject3.getString("room_id"));
    roomModel.setRoomName(jsonObject3.getString("room_name"));
    roomModel.setRoomStatus(jsonObject3.getString("room_status"));
    roomModel.setRoomimage(jsonObject3.getString("room_image"));

    // Log.d("room image", "———-" + jsonObject3.getString("room_id") + "——————" + jsonObject3.getString("room_image"));

    JSONArray jsonArray2 = jsonObject3.getJSONArray("switch_boards");
    List switchBoardModelList = new ArrayList();
    for (int k = 0; k < jsonArray2.length(); k++) {
    JSONObject jsonObject4 = jsonArray2.getJSONObject(k);
    SwitchBoardModel switchBoardModel = new SwitchBoardModel();
    switchBoardModel.setSwitchBoardId(jsonObject4.getString("switch_board_id"));
    switchBoardModel.setSwitchName(jsonObject4.getString("switch_board_name"));
    switchBoardModelList.add(switchBoardModel);
    JSONArray jsonArray3 = jsonObject4.getJSONArray("switches");
    List switchModelList = new ArrayList();
    roomModel.setSwitchBoardModelList(switchBoardModelList);
    for (int l = 0; l < jsonArray3.length(); l++) {
    JSONObject jsonObject5 = jsonArray3.getJSONObject(l);
    SwitchModel switchModel = new SwitchModel();
    switchModel.setSwitchId(jsonObject5.getString("switch_id"));
    switchModel.setSwitchName(jsonObject5.getString("switch_name"));
    switchModel.setSwitchType(jsonObject5.getString("switch_type_id"));
    switchModel.setSwitchState(jsonObject5.getString("switch_state"));
    switchModel.setIsFavourite(jsonObject5.getString("is_favourite"));
    switchModel.setIsScheduled(jsonObject5.getString("is_scheduled"));
    switchModel.setFanSpeed(jsonObject5.getString("regulator_value"));
    switchModel.setScheduleId(jsonObject5.getString("schedule_id"));
    switchModelList.add(switchModel);

    }
    roomModel.setSwitchModelList(switchModelList);
    }
    roomModelList.add(roomModel);
    }
    }
    Common.roomModelList = roomModelList;
    layoutManager = new GridLayoutManager(getActivity(), 2);
    recyclerView.setLayoutManager(layoutManager);
    roomsAdapter = new RoomsAdapter(roomModelList, getActivity());
    recyclerView.setItemAnimator(new FadeInUpAnimator(new OvershootInterpolator(1f)));
    recyclerView.setAdapter(roomsAdapter);
    swipeRefreshLayout.setRefreshing(false);
    }

    } catch (JSONException e) {
    e.printStackTrace();
    }
    }
    }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    swipeRefreshLayout.setRefreshing(false);
    // Toast.makeText(mContext, "" + "Please Login again", Toast.LENGTH_SHORT).show();
    }
    });
    AppController.getInstance().addToRequestQueue(strRequest);
    }

  3. Your Tutorial are really very helpful.please help me in following code.how to get Location in Android??Please provide the code sir??

  4. The examples posted here are very helpful for my app development.. But i’m really stuck here..
    i.e. I have two activities A and B.. which has a radiogroup each.. if i select a combination f,,one from A and one from B , it should direct to the next activity (i.e Activity C ) accordingly….Is there any way u can help me in this..????
    Thanks in advance 🙂

  5. hi im trying to develop android app where i have a launcher activity as main activity with login through google in third screen i’ve register button on register button click i want to open fourth activity as launcher activity but im unable please guide me.I wrote the intent in restart method but when app is killed its going to main activity

  6. HI All
    I would like to dis display list of questions by the user and Answers given by others for the corresponding Questions.

    On click My Questions it should display the list of Questions.If we click on each question it should display the Answers given by others in Android.Have any body done this earlier.if so,Can you please help me out?

  7. SIr I want to wirte a bluetooth application that scan and pair for incoming connection.If paired is complete I want to show message with Toast and change activity.And then,I want to be buletooth serial chatting.

  8. Sir, how can i add a multiple paragraph in a text view?
    I used string.xml. even i uses n , i couldnt add more than some lines. how can i rectify it?

  9. i am very beginner in android. your tutorial is very helpful for me. now, i need some tutorial on database using SQlite. Please give me some tutorial.

  10. Hi,
    I am trying to develop one small application in android which displays
    list of songs from specified path from sdcard or system path
    can u please help me out sir…

  11. Playing with Android controls, shifting between different screens, choosing layouts. After a tutorial such as this, a person who had prior experience with Java should be able to set up email or debug a real device.

  12. Hi..
    I need to develop an app which consists as follows:
    The wifi of my android phone should automatically on/off according to my saved location in the mobile.
    please help me …
    Thank you..

  13. HOW EXACTLY CAN I SHOW NAME COLUMN OF TABLE IN LISTVIEW.

    HERE IS MY CODE

    package
    com.jogidroid.testingcabsproject;

    import java.io.IOException;

    import java.sql.Date;

    import
    org.apache.http.client.HttpResponseException;

    import org.json.JSONArray;

    import
    org.json.JSONException;

    import org.json.JSONObject;

    import
    org.ksoap2.SoapEnvelope;

    import
    org.ksoap2.SoapFault;

    import
    org.ksoap2.serialization.PropertyInfo;

    import
    org.ksoap2.serialization.SoapObject;

    import
    org.ksoap2.serialization.SoapPrimitive;

    import
    org.ksoap2.serialization.SoapSerializationEnvelope;

    import
    org.ksoap2.transport.HttpTransportSE;

    import
    org.xmlpull.v1.XmlPullParserException;

    import
    com.sqlitedatabase.DatabaseHandler;

    import
    android.app.Activity;

    import android.content.ContentValues;

    import
    android.content.Intent;

    import android.os.AsyncTask;

    import android.os.Bundle;

    import android.util.Log;

    import android.view.View;

    import
    android.widget.TextView;

    import
    android.widget.Toast;

    public class GetVehiclesActivity extends Activity {

    private static String SOAP_ACTION = “http://tempuri.org/GetServerVehicles”;

    private static String NAMESPACE = “http://tempuri.org/”;

    private static String METHOD_NAME = “GetServerVehicles”;

    private static String URL = “http://favouritehatfield.co.uk/Service1.asmx?”; // “http://www.favouritehatfield.co.uk/Service1.asmx”;

    private TextView txtV_vehicles;

    private long clientid=46;

    private String response;

    private DatabaseHandler Objdbhandler;

    @Override

    protected void onCreate(Bundle
    savedInstanceState) {

    // TODO Auto-generated
    method stub

    super.onCreate(savedInstanceState);

    setContentView(R.layout.getvehicles);

    /** Show Toast at
    the Start of Activity… **/

    Toast.makeText(this, “WELCOME to
    GET VEHICLES ACTIVITY..”, 1).show();

    txtV_vehicles = (TextView)
    findViewById(R.id.txtV_lbl_vehicles);

    Objdbhandler = new DatabaseHandler(this);

    }//End onCreate()

    private class vehiclesAsyncTask extends AsyncTask{

    @Override

    protected void onPostExecute(Void
    result) {

    // TODO Auto-generated
    method stub

    super.onPostExecute(result);

    txtV_vehicles.setText(response);

    }//End
    onPostExecute()

    @Override

    protected void onPreExecute() {

    // TODO Auto-generated
    method stub

    super.onPreExecute();

    }//End
    onPreExecute()

    @Override

    protected Void
    doInBackground(Void… params) {

    // TODO Auto-generated
    method stub

    SoapObject
    getVehiclesRequest = new SoapObject(NAMESPACE, METHOD_NAME);

    // add paramaters
    and values

    PropertyInfo
    pi = new PropertyInfo();

    pi.setName(“defaultclientId”);

    // pi.setValue(clientid);

    pi.type= PropertyInfo.LONG_CLASS;

    getVehiclesRequest.addProperty(pi,46);

    PropertyInfo
    pi2 = new PropertyInfo();

    pi2.setName(“hashKey”);

    // pi.setValue(clientid);

    pi2.type= PropertyInfo.STRING_CLASS;

    getVehiclesRequest.addProperty(pi2,”464321orue”);

    // getVehiclesRequest.addProperty(“defaultclientId”,
    46);

    // getVehiclesRequest.addProperty(“hashKey”,
    “464321orue”);

    SoapSerializationEnvelope envelope
    = new
    SoapSerializationEnvelope(SoapEnvelope.VER12);

    envelope.setOutputSoapObject(getVehiclesRequest);

    envelope.dotNet = true;

    HttpTransportSE httpTransport = new HttpTransportSE(URL);

    //httpTransport.debug = true;

    try {

    httpTransport.call(SOAP_ACTION, envelope);

    } catch
    (HttpResponseException e) {

    // TODO Auto-generated
    catch block

    e.printStackTrace();

    }
    catch (IOException e) {

    // TODO Auto-generated
    catch block

    e.printStackTrace();

    }
    catch
    (XmlPullParserException e) {

    // TODO Auto-generated
    catch block

    e.printStackTrace();

    }

    try {

    SoapPrimitive
    result = (SoapPrimitive) envelope.getResponse();

    response = result.toString();

    Log.i(“response”, response + “”);

    JSONObject
    jsonObject;

    try {

    // jsonObject
    = new JSONObject(response);

    // Log.i(“jsonObject”,
    jsonObject + “”);

    // Getting JSON
    Array from response

    JSONArray
    jsonArray = new JSONArray(response);

    for (int i = 0; i <
    jsonArray.length(); i++) {

    JSONObject
    res =
    jsonArray.getJSONObject(i);

    // Storing JSON item in a Variable

    String
    Id=res.getString("Id");

    String
    Name=res.getString("Name");

    String
    TotalPassengers=res.getString("TotalPassengers");

    String
    TotalHandLuggages=res.getString("TotalHandLuggages");

    String
    TotalLuggages=res.getString("TotalLuggages");

    String
    SortOrderNo=res.getString("SortOrderNo");

    Log.i("Id", Id);

    Log.i("Name", Name);

    Log.i("TotalPassengers", TotalPassengers);

    Log.i("TotalHandLuggages", TotalHandLuggages);

    Log.i("TotalLuggages", TotalLuggages);

    Log.i("SortOrderNo", SortOrderNo);

    Objdbhandler.saveVehicles(Name,
    TotalPassengers, TotalHandLuggages, TotalLuggages, SortOrderNo);

    }//End for loop

    }
    catch (JSONException e) {

    // TODO Auto-generated
    catch block

    e.printStackTrace();

    }

    }
    catch (SoapFault e) {

    // TODO Auto-generated
    catch block

    e.printStackTrace();

    }

    return null;

    }//End
    doInBackground

    }// End
    vehiclesAsyncTask

    /** Called when the
    user clicks the GetVehicles button */

    public void getVehicle(View v) {

    String str = "You have clicked GetVehicles
    …";

    Toast.makeText(this, str, 0).show();

    vehiclesAsyncTask
    vehiclesRequest = new vehiclesAsyncTask();

    vehiclesRequest.execute();

    }//End getVehicle()

    public void listViewBtnClick(View v) {

    Intent
    i = new Intent(this,ListVehicleActivity.class);

    startActivity(i);

    }
    //End
    listViewBtnClick

    }//End class
    GetVehiclesActivity

  14. hi sir,iam Ramesh.b iam doing dummy project of metro trins in this iam using two spinner one is source station another one is destination stations when iam click find trains button i want open another page display train timings. same as it is if select different source and different destination display like that pages please help me

  15. Your tutorials are amazing. Could you please make tutorials on mySQLite database and how to save data from radio buttons, date picker and the likes.

  16. Nice Tutorials..But still need Sqlite db ,Webservices,Xml parsers,Orientation changes ,How to create dynamic layout via Java code ,Fragmentation,Gmaps ,Camera etc ..We want more

  17. How can i randomly change the current activity Layout when i click a Button ? i don’t really know how and where to start coding.

  18. please check this code what is wrong with this code, when i scroll listview randomly checkboexes selected at random position automatically….
    I will be thankful for your kind help…………

    private class ListAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {

    private SparseBooleanArray mCheckStates;
    LayoutInflater inflater;
    ViewHolder viewHolder;
    CheckBox cb;

    public ListAdapter(Context context) {
    mCheckStates = new SparseBooleanArray(arrayContacts.size());
    inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
    // TODO Auto-generated method stub
    return arrayContacts.size();
    }

    @Override
    public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
    }

    @Override
    public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View rowView = convertView;
    if (rowView == null) {
    inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    rowView = inflater.inflate(R.layout.listview_row, null);
    cb = (CheckBox) rowView.findViewById(R.id.checkox);

    cb.setTag(position);
    cb.setChecked(mCheckStates.get(position, false));
    cb.setOnCheckedChangeListener(this);

    viewHolder = new ViewHolder();

    viewHolder.txtName = (TextView) rowView.findViewById(R.id.txtdisplaypname);

    rowView.setTag(viewHolder);
    }
    else{
    viewHolder = (ViewHolder) rowView.getTag();
    }
    viewHolder.txtName.setText(arrayContacts.get(position).getContactName().trim());

    return rowView;
    }

  19. hi mkyong
    i’ve a class library in c#.net and i want to import this dll into eclipse project and use it function in android activity,
    how can i do it?

  20. Hi,
    I have a text box. But I want to connect my phone’s contact list to this Text-box.
    So, when user clicks on this text box, he can select the contacts available.
    On top of this, I would like to have multiple selection of contacts within the same text box.

    Can you please guide.

    Thanks
    Saurabh

  21. Android Developer? StartApp offers the best app monetization and now you get a great sign up bonus! . It is an icon ad network, and they pay on per download basis.
    Get bonus $15 for the first 1000 downloads with my referral link here: http://startapp.com/rf4hfnr

  22. Your site is very useful to learner for android developer. I learned android from yuor site. I am very much disappoint because you didn’t update your android tutorial for long time. I am waiting for updated tutorial much for ……

  23. For Google Tranlaters this is Portuguese – Brazil.
    Rapaz, seu site é realmente incrível… Adorei. Acabei de me formar e estou iniciando alguns projetos em Android. Simplesmente adotei grande parte do seu material.
    Conte comigo caso precise de ajuda para editar algum arquivo ou post.
    Um Abraço!

  24. sir, i’m an I.T student and i want to make an android apps for reservation using MySQL database. and i don’t have any background of java. can you please help me.

    can you show me the code of adding products/reserving using android and by using MySQL database….thank you very much…

  25. Can you tell me how to access list collection from asp.net web service into android application.i am trying using ksoap.jar file but problem is that web service is working fine but i can’t get that list collection in android app.please give me replay as soon as possible

  26. sir if u can please show the code about XML parser,JSON parser,u give the simplest way to solve the problem please,thanx in advance

  27. The site is very helpful but it can be much better if the part of database connectivity has also been covered in these tutorials.

  28. This nice tutorial. but sir can you put web services request and responses example with explanation that would be help for us a lot.

    Thanks

  29. Hi sir
    I want to send digital serial via Bluetooth to my MicroCont .can you please sent a prog for this.

    thanking you

  30. Hi ,

    How to send Image from android apps to Server using Socket datainputstream, In server receive the image & store it drive , I tried alot but it not help me out please help me out

    thanks
    bhagavath

    1. Try this it’ll help u

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);

  31. hello ,sir can you help me to create a photo albums and how i can add albums to classify photo !!!! 🙂

  32. Sir, your tutorials are very helpfull for me.
    but i need a tutorial on framents.
    can you please give the tutorial on fragments

  33. 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…..

  34. 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

  35. sir I need a help regarding
    I want to display multiple(4) buttons randomly on screen
    every button created in java file extend views

  36. 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

  37. 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

  38. 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……………….

  39. 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 🙂

  40. 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

  41. 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();
    }
    });

  42. 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?

  43. 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

  44. 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

  45. Hello sir its very interesting to learn android from your tutorials and its great experience to learn android through your tutorials thank you sir

  46. 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.

  47. 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

  48. Hello frnz,
    I need an urgent help. I want to create a login page with name, mobile no, email id. I need to store it on web server database(using mysql). When the user uses the app again, he don’t need to login again.. The app should check for his validation in the created database and take him to the next page automatically. If any of you or your frnz can help me out in this then please post the code here or mail me at [email protected]. I have tried JSon and http method but its not getting posted on the server.

    1. Generally this type of logic is implemented using localstorage and not by Web Server.
      Advantage of using localstorage instead of Web Server is you can readily save / retrieved the login information (provided the login is successful). There is no need to make two way MySQL query to store / fetch for future login.

      If you still want to use MySQL on WebServer, You can try doing like this…
      It is not difficult.
      I have made use of jQuery and getJSON
      Below code is for Login Page front end JavaScript placed at the end of the page

      <script>
      $('#signup').bind('pagecreate pageshow',function(event){
           $('#BtnSubmit').bind('click',function(){
                var form = $('#LoginForm');
      	  var formData = form.serialize();
      
      	  $.getJSON("http://www. [[yourserver address]] .com/ [[you PHP script login.php]]?callback=?",FormLogin,
      	     function(data) {
                       alert(data);
                      //based on this data you can redirect the user to next page
      	  });
           });	
      });	
      </script>
      

      For the above code to work, you need another file on your web server, say for example login.php, in this PHP file you just use routine PHP and MySQL code to determine the POSTED data from the Login Form, Search your MySQL database and then based on result you set and return a value.

      Hope this helps…

    2. for this problem have one way solution
      1. using row count function.
      first time your row count is zero then we insert value in database.
      2. when you application start on second time that time if your row count is greater then 0(zero) that time you van use or give next page address.

  49. hello…
    i want to create google map event handling application..
    plz , can u tell me about how to use javascript in android app for google map v3.

  50. Good evening sir

    what a tutorial sir before seeing in your blog i am afraid about android but now i understood very well !!!!!!!!!!!!!!!!!!!!

    Thank your so much for giving this tutorial

  51. First of all i should say thank you to you such wonderfull tutorial especially Andriod Apps. and also i have question that is how to input the other laguage keyboard such “Tamil,…” on android devices? is that posiible? the please let me know if you have any idea about this.

    this is my e-mail id: [email protected]

  52. hi could u tell me is it easy to learn android basics & related to android everything & is there anything more which u had provided in ur material

  53. thank u sir.
    your android tutorial help me a lot as a beginners.
    will u please upload tutorials like SQlite , animation,
    service etc.
    thank a lot for uplift my confidence in android

  54. How can I overcome deprecation of TabActivity in version Android 4.1.2…??? please reply me 🙂

    Thanks and regards,

    Sachin Bharadwaj

  55. Dear Sir,
    Let met know how android is simulated on wireless ad hoc network. Does Android work together in NS -2 simulator? Can anyone can suggest me on implementation mobile device on network simulation tools. Thank in advance.

  56. hi mkyong,your website is providing a lot of knowledge to all beginners in programming language.would u plz post some advanced topics on android it will very much usefull 2 me & for the Android developers

  57. hi sir,
    i am new to Android , I making program in android that is for calculating the average
    of 8 numbers which having only one edittext and one button
    after taking the all numbers from users one by one it display the result on same edit text box

    1. Hi ,
      Just enter the values with comma (,) as delimiter in the EDIT TEXT when button is clicked , in this click event handler use StringTokenizer with comma(,) as delimiter and parse to their values and compute.

  58. Thanks a lot.Your tutorial helped me a lot as a beginner in Android.

    but now please provide more example to create app like Google map navigation,make a music player,voice recording,etc….

  59. I love your website. It always helps me to learn and create an interactive android mobile applications.

    Thank you dear sir and co.

    By your friend Jona from Yellagiri

  60. Nicely presented tutorials. Very good for the complete novice.
    Would it be possible to produce a tutorial that explains how to place icons on the status bar.
    For example, a battery status indicator showing a percentage of power?
    Keep up this great resource.

  61. thank you sir for your valuable sharings…….Can you help me to implement an ExpandableListView in which the groups will be automatically closed while we are opening any other group… Please sir, I am expecting help from you…

  62. Thnk u sir…
    Thnk u so much…
    Because of this tutorial nw i m understand android properly….
    n sir pls upload other tutorial for android like Animation,SQLite and other Dynamic tutorial…

  63. hi,,,

    You provide such a great resource ,,,which really helps..Thanks!!!!!!!!

    I am doing a project on Android XML data parsing and showing them in Customised ListView
    Would You provide Some help for the same…as I am Novice to Android….

    Thanks!!!

  64. Its very useful tutorials and this help in efficient way
    so please try to give me more to help me improve my my skills in android programming…
    Best regards…

  65. hello,

    What is a Mashrey URL ?
    We are advised to use something of this kind for OAM authentication.

    Thanks and Regards,
    Hari

  66. Awesome tutorials for beginners to get some confidence about android programming.

    Hats off to you mkyong.

    Please keep posting new programs like twitter and other apps as well.

    Thanks a lot
    Vijay

  67. ca u give me a stepwise of hoe to create an android code?how to compile and how to run?
    plz…………………

  68. I am using webserivce to access android application using ksaop jar file. When I install into mobile the jar file also need to install into mobile ?. Please send me solution.

  69. i am new to android and i have done an image gallery with zoomin.its working properly for small number of images.but when i increase the size of the number of images in gallery its showing “force close” and project will be closed.what can i do for this problem

  70. Sir,
    Is it possible to fetch myphpadmin’s mysql data from android device directly like Jdbc connection in java.?I am not asking for sqllite connection.
    Please reply me asap.

  71. These are great tutorials and they have been a great help to me personally. Could you please write a post on its database connection and its use please. That would be really helpful and would actually complete the basic tutorial for android app development. Thanx in advance.

  72. Hi MyKong,I want Android Application works as a Scheduler. i.e to fire an action when some System time is set. Could you please guide me how to go about it. I have created an Intent Also if my Android App is minimised will it be able to receive notification of the time, how to do about it.

  73. hi,

    Can you help me to develop an android application having horizontal scrolling for gridview ?
    or any useful links ???

    Many people are suffering on this topic…

    Thanks in advance?

  74. Hello Sir,
    I am learning Android and your tutorials are good for learning.
    Sir, I want to connect a USB device to my Android-phone and receive data on my phone. Could you please help me how should I go about with it??
    Thanks.

  75. Dis is gr8 tutorial 2 start developing android application.
    It’s really a fun developing applications.
    I develop android apps in my smartphone.
    Thanx a lot mkyong!!!

  76. hi sir, i'm student from ina.
    i wanna ask about "how to call random class on android?" when i click button.
    and how to make a multiple choice for a quiz on android??
    hope u'll help me :)
    
  77. Hello,
    how to copy file from asset folder to /data/local/tmp and chmod all file is copying to 777, if sdcard is can copy but not chmod 777,

  78. i have created android Calculator app in Eclipse. if i want to run that app i need eclipse must and should.

    But i want to make that app run without eclipse in any system as a normal apps run .

    just download and run then time app has to be run.

    If any one knows help me Pls

    1. If I start my emulator, my Eclipse apps still work. But if you need the “release version”, you need to look in your project for a file with the same name as your project and the extension APK.
      Upload it somewhere and people can download this APK file which will install the app on their phones.

  79. Please upload the program to make a ProgressDialog without the numbers (20% 30/100). I know this can be done by extending the progressdialog class but that is where my knowledge ends.

  80. i knw how to zoomIn but going ti infinite n its dragging….i dnt want to drag n i dnt want to zoom out the current image..and i need to ZoomOut the extended image,,,please can u help me…thanku

  81. how I can make application android with langue arabe cos I try many time and it doesn’t can read it…plz any idea

  82. Hello,

    This is really a great work done by you without expectations and with an attitude of letting the newbies know about in and out of the basic features of Android.

    This is really a web page that a newbie should start from.

    Thanks for all your hard work and looking forward for your further webpages.

    Regards,
    Arun.AR

  83. Hi,
    I am beginner in Andriod programming. I would like to know how long it will take to see the result of Andriod program. Now, it takes about 15 minutes to see the result for me. That makes me so impatient. So, I also want to know whether andriod programs takes long time and how I fix this problem.

    My system ….
    320 GB HDD
    2 GB Memory

    I would like to know next system requirements are required for andriod. Thank in advance.

      1. u r tutorial is such a helpful that any begginner easily grasp all of the basic concept.i really salute to u r hard working.

  84. Hi mkyong
    I am starting to write first application for android and do not exprience
    for first job add a clock and set alarm system
    tanks a lot help me help me

Leave a Comment

Your email address will not be published. Required fields are marked *