Login Application For Android

Last week my friend was stuck for an Android application. That application was to use the remote database (MS SQL Server) for login.

Later I saw the coding of Android, which was Java only. Its much like just another Java framework. So I thought to give a try to help him and even I could learn some Mobile Application programming.

As Android provide flat file data storage or SQlite for data storage, it was quite tough to access the remote database like MSSQL Server, Oracle or MYSql.

Later I found in newtondev that we can execute GET or POST request from the android page and get the output of the requesting page. This lead me to the solution.

I sends the form data from Android application to the Server-side page (JSP, Servlet,ASP or PHP), then those page will compile the required operation for login validation using any database , then it returns “1” if the login is valid else return “0”.

Here are the source codes that will give you Idea for the application.

Application -> res -> layout -> main.xml (interface for Android)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="210dip"
    android:layout_marginTop="10dip"
    android:background="#DDDDDD">
    <TextView
        android:id="@+id/tv_un"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="9dip"
        android:layout_marginTop="20dip"
        android:layout_marginLeft="10dip"
        android:text="User Name:"/>
    <EditText
        android:id="@+id/et_un"
        android:layout_width="150dip"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@id/tv_un"
        android:layout_alignTop="@id/tv_un"/>
     <TextView
        android:id="@+id/tv_pw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/tv_un"
        android:layout_marginRight="9dip"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="10dip"
        android:text="Password:"/>
    <EditText
        android:id="@+id/et_pw"
        android:layout_width="150dip"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@id/tv_pw"
        android:layout_alignTop="@id/tv_pw"
        android:layout_below="@id/et_un"
        android:layout_marginLeft="17dip"
        android:password="true"        />
    <Button
        android:id="@+id/btn_login"
        android:layout_width="100dip"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_pw"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="110dip"
        android:text="Login" />
     <TextView
        android:id="@+id/tv_error"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:textSize="7pt"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/btn_login"
        android:layout_marginRight="9dip"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="15dip"
        android:textColor="#AA0000"
        android:text=""/>
</RelativeLayout>

Application -> src -> com.example.login -> LoginLayout.java

package com.example.login;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginLayout extends Activity {
    EditText un,pw;
	TextView error;
    Button ok;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        un=(EditText)findViewById(R.id.et_un);
        pw=(EditText)findViewById(R.id.et_pw);
        ok=(Button)findViewById(R.id.btn_login);
        error=(TextView)findViewById(R.id.tv_error);

        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            	ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            	postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
            	postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));

            	String response = null;
            	try {
            	    response = CustomHttpClient.executeHttpPost("<target page url>", postParameters);
            	    String res=response.toString();
            	    res= res.replaceAll("\\s+","");
            	    if(res.equals("1"))
            	    	error.setText("Correct Username or Password");
            	    else
            	    	error.setText("Sorry!! Incorrect Username or Password");
            	} catch (Exception e) {
            		un.setText(e.toString());
            	}

            }
        });
    }
}

Application -> src -> com.example.login ->CustomHttpClient.java (from newtondev)

package com.example.login;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class CustomHttpClient {
	/** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Since the application will not be allowed to access the Internet (remote service). So we have to add permission using following line to the AndroidManifest.xml


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

So that the AndroidManifest.xml look like this.


<?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="com.example.layout"
           android:versionCode="1"
           android:versionName="1.0">
       <uses-permission android:name="android.permission.INTERNET" />
       <application android:icon="@drawable/icon" android:label="@string/app_name">
       .
       .
       .
       </application>

</manifest>

Then on the server-side we can check login by using password. But here in this example I have use a simple servlet, which check the static login.

package web.com;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Prashant
 */
@WebServlet(name="AndroidResponse", urlPatterns={"/androidres.do"})
public class AndroidResponse extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String un,pw;
        un=request.getParameter("username");
        pw=request.getParameter("password");
        if(un.equalsIgnoreCase("prashant") && pw.equals("sharma"))
            out.print(1);
        else
            out.print(0);
    }
}

Output :

<?xml version=”1.0″ encoding=”utf-8″?>

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:layout_width=”fill_parent”

android:layout_height=”210dip”

android:layout_marginTop=”10dip”

android:background=”#DDDDDD”>

<TextView

android:id=”@+id/tv_un”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:textSize=”10pt”

android:textColor=”#444444″

android:layout_alignParentLeft=”true”

android:layout_marginRight=”9dip”

android:layout_marginTop=”20dip”

android:layout_marginLeft=”10dip”

android:text=”User Name:”/>

<EditText

android:id=”@+id/et_un”

android:layout_width=”150dip”

android:layout_height=”wrap_content”

android:background=”@android:drawable/editbox_background”

android:layout_toRightOf=”@id/tv_un”

android:layout_alignTop=”@id/tv_un”/>

<TextView

android:id=”@+id/tv_pw”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:textSize=”10pt”

android:textColor=”#444444″

android:layout_alignParentLeft=”true”

android:layout_below=”@id/tv_un”

android:layout_marginRight=”9dip”

android:layout_marginTop=”15dip”

android:layout_marginLeft=”10dip”

android:text=”Password:”/>

<EditText

android:id=”@+id/et_pw”

android:layout_width=”150dip”

android:layout_height=”wrap_content”

android:background=”@android:drawable/editbox_background”

android:layout_toRightOf=”@id/tv_pw”

android:layout_alignTop=”@id/tv_pw”

android:layout_below=”@id/et_un”

android:layout_marginLeft=”17dip”

android:password=”true”        />

<Button

android:id=”@+id/btn_login”

android:layout_width=”100dip”

android:layout_height=”wrap_content”

android:layout_below=”@id/et_pw”

android:layout_alignParentLeft=”true”

android:layout_marginTop=”15dip”

android:layout_marginLeft=”110dip”

android:text=”Login” />

<TextView

android:id=”@+id/tv_error”

android:layout_width=”fill_parent”

android:layout_height=”40dip”

android:textSize=”7pt”

android:layout_alignParentLeft=”true”

android:layout_below=”@id/btn_login”

android:layout_marginRight=”9dip”

android:layout_marginTop=”15dip”

android:layout_marginLeft=”15dip”

android:textColor=”#AA0000″

android:text=””/>

</RelativeLayout>

490 Responses to Login Application For Android

  1. Nice blog buddy with complete code , thanks for sharing information.

    Javin

    • Rohit says:

      Hi

      this is nice post, but can anyone help me out here. can i know where and how should AndroidResponse .java file should be written. i am new to android programing.

      Rohit

      • Prashant says:

        Response java page can be jsp or servlet, where you will get POST or GET values using request.getParameter(“”).and after operating posted value, print plain-text which will return as response to android.

    • Ram says:

      Nice one …

    • sushant says:

      hii how can connect with .php file on server any idea

      • Prashant says:

        Send http response As Jason, and use jason to validate. that will make things easier. Thanks.

  2. viraj says:

    i like this ..
    i want to know more about relative layout…
    how to use good alignment ??
    also i couldn’t get http request and all.

  3. Chris says:

    Great Tutorial. Helped me a ton!

  4. sameera says:

    hi prashant,
    this code is not working for me
    i m using eclipse n with in the same project i made web.com package n their i put android response file..
    is it correct?
    and whenever i login it gives me a msg of login failed…
    i gave user permission also in manifest
    Please suggest…

    • Prashant says:

      Hi sameera,
      if you are putting that HTTPClient, then it is fine. But the Servlet should be in webserver.

      • sameera says:

        Thanx Prashant for ur reply!
        Here we are using servlet
        but I need to build login application using mysql database and php….
        I have done with my mysql database and php code
        but im not getting how to fetch database entries in android for login
        can u help me out 4 dat also??

      • Prashant says:

        In php page, just check the posted value from android is correct or not. If correct echo “1” else echo “0”
        now, if you are getting the response as 1, then login success else failure
        And dont forget to trim white character before checking.

      • engiguide says:

        Hay Prashant thanks for grate article… i have same question as sameera..

        What about if i want to use php .. i see ur answer for that but can you please explain this thing in details…??

        Will appreciate your help 🙂

      • Prashant says:

        Hello engiguide,
        I think you have doubt about the posting to PHP.
        suppose if you are are using “username” and “password” while posting the dfata,
        from php you have to use $_post and compare it with database username.
        if fit succeed, it will echo “1” or “0”
        now in android, you have to trim the blank space and check whether you got “1” or “0”
        according to that, you have to process next action.

        and GPS example, I will post it after few hours and will give you URL to link.

      • engiguide says:

        this is mu code… check it… and i want to ask .. how can i get value from LoginLayout.java.. file with
        ID = password and username or text box id…tv_un , tv_pw
        thanks fro replay .. i think i am near to solution.. help me ./…:)

      • Prashant says:

        if you see in 36th and 37th line LoginLayout.java, you can see that I have added those tv_un values into the username.
        which means, when it passes to server, it will pass as username=tv_un.getText();
        and when I am requesting for the page, i will be requesting along with the parameter.
        now it is the task of php page to access those posted value.

      • engiguide says:

        check out my code,… and give some suggestion….

        see i got that your code posting data with username and password… but in servlet i am new… what is the meaning of 15-20 line code… is it something that i required to add in php …
        thanks .. Prashant for your last replay… will wait….:)

      • engiguide says:

        also can you mail this code.. may is there any copy past problem ….. 😦

        ajaypatel_aj@yahoo.com

    • engiguide says:

      Hay prashnat …. after all i solved it….

      You know … what is my mistake… is …

      if you are using.. ann function in your page than your return code is work.. as in your servlet

      [ oup.print(1) ] instead in php i am writing [ return 1;]… and its my mistake… that i am not using [ echo 1 ]….as ur code in servlet[out.print(1)]

      So now.. happy 🙂
      And thanks thanks lot for this kind good post.. it will really help full for making web services.. ….

      if any one want my php code mail me to ajaypatel_aj@yahoo.com.

      Thanks
      Ajay

  5. speed says:

    Your article was very helpful. I recently had to use Android to access existing .NET Web Services (SOAP). Android does not natively have SOAP access. I tried Ksoap and other solutions and nothing worked. I finally found WSClient++ from Nuerospeech, which allows the instant creation of a SOAP client for Android. You just point it at your WSDL and it does the rest. It has saved me a lot of time and frustration dealing with SOAP within Android. Here is the link if you are interested:
    http://wsclient.neurospeech.com/

  6. raghav says:

    HI Prasant ,
    can u reply with the structure of this programme/project

    plz reply

    • Prashant says:

      Hi ragav,
      There are mainly four files in this project. First one is main.xml in res/layout. Another two java files will be in package inside src. And third file will be in web-server which will executed by CustomHttpClient.

  7. sameera says:

    thanx prashant my application is finally working!

  8. Voula says:

    Hi Prasant ,

    could you please tell me where do i have put the file with servlet? I can’t understand. My page is login.aspx but the message i take all the time is :Sorry!! Incorrect Username or Password.
    Thank you in advance

    • Prashant says:

      Hello Voula,
      If you are using asp page, you don’t need servlet. In LoginLayout.java, on 41th line you can see . So you have to give full url (http://…..) of your asp page. and the logic will be written in the asp page whether to return 1 or 0. If you are not getting correctly, just print 1 from asp page and try this tutorial. And most important thing is to return in plaintext. if you are not print in plane text, it may return you with some html tags which will lead to invalid login.

      • Voula says:

        Hi Prasant,

        First of all, thank you for your quick reply. 🙂
        I have put the full url of my page, but i cant understand exactly what could i do in my aspx page. In my aspx page, in code behind, i have check if return 1 then redirect to another page.
        Could you please write some sample code about this?
        sorry but i think i cant understand because i’m newbie in this.

        Thank you very much!

    • Prashant says:

      Hello Voula,
      Actually I dont know .net. But I can tell you the process.
      You might had seen that we are posting the data with postParameter. You will get the posted value in the asp page. and after that you can check the posted data for verification then you will print the result of the varification 1 or 0. what ever you print that will result to ‘response’ variable.

      • Voula says:

        Hi Prasant,

        Thanks for your help. I will check and let you know if I need anything else.

        Thanks again,

        Voula

  9. Voula says:

    Hi again,
    i tried this but with no result.
    I tried to print the “res” and the result is all the html page with html tags etc..
    i dont know what can i do about this.
    sorry for the inconvinience but you may know what i have to do about this.
    thanks again,
    Voula

    • Prashant says:

      Hello Voula.. to get result as plane text in .net you should use this line
      Page.Response.ContentType = “text/plain”

  10. Ramji says:

    where we put server-side servlet program ?? pls help me.

    • Prashant says:

      You have to upload it in webserver, and in LoginLayout.java, 41th line you have to provide the url of the servlet.

      • Abhinov says:

        even i have the same doubt as ramji where will be the web server in ecllipse……….where should be the server side code dont just give me rly as web server i am nt getting it.so plz explain me………i want a clear explanation of project structure of the server ………………
        thanks in advance………..

  11. AndroidAnnie says:

    I had high hopes for your excellent example, Prashant, especially as it compiles just fine.

    However, when I attempt to run it in my emulator, I’m getting the following force shutdown error. The dugger reports that it cannot find source for “android.jar.” Does this make sense to anyone?

    • Prashant says:

      Source not found error mostly appear as Null Pointer Exception. Check whether all the component is initialized or not.

  12. Raghav Rajagopalan says:

    Hi prashanth!!

    I am Raghav Rajagopalan from Chennai. I am new to Android environment.I need a small login script where user input(User name and Password) is checked in server and return ID as output from server and based on ID we need to display the message(Logged in). I am using KSOAP2 for web service in .net code.

    Thanks in advance!!

    Regards,
    Raghav Rajagopalan

  13. prachi says:

    hi prashant

    i try to run ur codes on emulator bt it stop unexpectedly i don’t know why plz help me as soon as possible.
    thanks

    • Prashant says:

      This may appear, if you are not getting any response string from the server. As the response is null, it may unexpectedly close and displays “Source not found”.

  14. prachi says:

    hiiii prashant
    my app is running now,getting response frm server bt it always shows incorrect username & password even when password & user name is correct.plz help
    thanks

    • Prashant says:

      while returning the response… convert it to plain text.. and in the android, trim all the space before checking…

  15. Ankit says:

    based on your response to Prachi on 8th April 2011, I want to know where you are converting the response into plain text in your above mentioned code and what do you mean by trim white space like how to trim all the white space, do we need to do something in our layout xml file or in our layout java file to trim the white space.

    • Prashant says:

      in .net to response as planetext you have to write
      Page.Response.ContentType = “text/plain”
      and in java
      if you don’t convert response to text/html it will be plane text.

      and trimming is required to do with the response we obtain in android.
      sometime it response one blank line with the response.

      • Gaya says:

        please need more about trim or remove white space for me,because I am a newer…….

      • Prashant says:

        Hi Gaya,
        please visit this URL
        http://www.roseindia.net/java/beginners/StringTrim.shtml

        you can get lots of simple tutorial regarding this.

      • Gaya says:

        Related to my post……….
        I got same error “always shows incorrect username & password even when password & user name”.I could not solve it.please help me

      • Gaya says:

        Thank you for your quick reply Prashant,
        Ok i have done about that.I have did as you did,
        String res=response.toString();
        res= res.replaceAll(“\\s+”,””);
        if(res.equals(“1”))
        error.setText(“Correct Username or Password”);
        else
        error.setText(“Sorry!! Incorrect Username or Password”);

        But, I couldn’t solve the problem.Can you tell what are the errors sending always incorrect message.Please help me to solve this problem.

      • Prashant says:

        once set the error message to display the response from the server.
        So that you will come to know actually what you are receiving from server.

        error.setText(res);

      • Gaya says:

        Hey Prashant,
        You saved my life….Thank you so much dear….
        You had a error in your code in following line,

        res= res.replaceAll(“\\s+”,””);

        It should be change as,
        res= res.replaceAll( “[\\D]”,””);

        I have corrected in my code as this.Then it has done very well.
        Thanks again…….

  16. Ankit says:

    Thanks prashant for your quick reply…will get back to you if I get stuck…!!!

  17. Renjith says:

    Hi Prasanth,

    Thank you so much for the program. Unfortunately when I tried to execute the program I got few errors. I have fixed many of them. Still I got 2 more errors.
    1. “Description Resource Path Location Type
    Conversion to Dalvik format failed with error 1 AndroidLogin Unknown Android Packaging Problem

    2. “Description Resource Path Location Type
    id cannot be resolved or is not a field HelloAndroidTest.java /HelloAndroidTest/src/com/example/helloandroid/test line 19 Java Problem

    Am very new to Android development. Could you pls help me out finding a solution in executing this program ?

  18. Riadh says:

    salut a tt ,un grant merci pour c tuto ,svp quelqu’un que peut m’aider ,j’ai copier coller c code et j’ecrit un servlet avec le serveur tomcat .mais toujour un probleme
    merci d’avance.”application authentification has stopped enexpectly please try egain”
    svp qu’elqun qui c projet compressé me lui envoyé
    merci d’avance

  19. Riadh says:

    Pracha hello, thank you for this tutorial, I speak french, sorry, I need help, I copy and paste this code but its not working can you help me if you pleasure

  20. Riadh says:

    I test it in Android 2.1 and 1.6 and 3

  21. Riadh says:

    I have a project end of study, I have 15 days and I need this toturial. Pracha thank you in advance

    • Prashant says:

      Okay riadh, check your gmail account I have sent you this example. But serverside code, you have to write yourself and upload into your web-server.

  22. Naresh says:

    hi prasanth…..i am new to android application dev .I am developing an android application which is associated with website.in my home screen there are two buttons login and register.if i clicks on register it should take all user details and save it into remote sql server.for that how to start coding.how should i approach?pls help me out with step by step process.

    • Prashant says:

      This tutorial is one of the way where you have to make user of a serverside where it will receive the submitted data.
      but the effective way is to user web-services, but i dont have any idea about web-service method.

  23. Clarence says:

    Hey, this tutorial is helpful, i just started to learn android programming and i would like to ask why i have a red exclamation mark for all the “import.javax.servelt” .? and where can i insert the last section? the simplet servelet part .

    • Prashant says:

      That may be orange underline, to indicate that you have imported the library but not yet used.
      the servlet will be in the webserver, where your web apps resides.

  24. Clarence says:

    Thanks a lot =D

  25. hsyn says:

    i got some error.It’s java.net.SocketException:permission denied.How can i resolve this problem

  26. hsyn says:

    meantime i used php for serverside,is that problem

    • Prashant says:

      PHP is not any problem.. but the permission… i have suggested Internet Permission in the example.
      It seems you have not given the permission…

      • hsyn says:

        i did it i have wrote permission code for androidmanifest.xml

      • Prashant says:

        once try to give the server side page url using ip address and port number..

      • Tazeen says:

        Hi I,m Tazeen here . I’m beginner in Android I implemented your example but I got error . I don’t why. I create AndroidResponce class in Dynamic web project but since I got error. I want to retrieve jsp page in my android. Can you guide me properly how to do this. I don’t know how to use jsp in Android. Please can you help me. need urgent help. Thanks you.

  27. hsyn says:

    i got new error org.apache.http.conn.HttpHostConnectException:Connect to http://localhost refused

    • Prashant says:

      Ohh.. you are trying with localhost? then instead of localhost, you have to give ipaddress 127.0.0.1:PortNumber

  28. hsyn says:

    ıt’s still same error :S

  29. hsyn says:

    i am using 80

  30. hsyn says:

    i changed port number but i got same error.i am using iss for php.i checked php.it’s running

  31. hsyn says:

    yes :S

  32. saru says:

    i m getting an error while i click the login button..
    “java.lang.IllegalArgument Illegal character in scheme at index 0:
    AndroidResponse is the name of the servlet(and the name of the folder containing it) i have created.
    please help!

    • Prashant says:

      that means you are not getting any response from the servlet, it is null.
      Please check with the URL that you have given for request, and whether it is responding any data or not.

      • tina says:

        i getting the same error
        where is given the url for request?
        please help me up, I’ll be very grateful

      • Prashant says:

        Are you trying for localhost url or web url? If it is localhost, you have to give IP address. If it is web-url, once you can check in browser, before running into android.

  33. Hi Prashant!
    I m new in android application. I don’t much more knowledge in android. Plz tell me How can access .net webservice in android application.?
    when my application run then output is false.
    what is means?
    Plz give me My answer….
    I hve not nobody giving me support..
    Your’s sincerity
    Bvenkat Jeewesh

    • Prashant says:

      Hello Bvenkat,
      Actually in this example, no web service is used. I am just executing the httpPost.
      But you can use webservice, which is the better option.
      I think this video will help you nicely to understand use of web service for android.
      http://vimeo.com/9633556

  34. Thanks for Reply.. Actually I Saw this video earlier. still i couldn’t get the solution. If u have some other solution then plz let me know…
    Regards
    Bvenkat Jeewesh

    • Prashant says:

      by the way, what is the error you are getting??
      Actually, I dont have .net knowledge so unable to help you with .net web service code.
      If you are using same example as the video (web service with w3schools example), please send me your zipped source project.

  35. This is my full code. Plz find out where is error?
    package com.first.mytestdemo;

    import android.app.Activity;
    import android.os.Bundle;
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapPrimitive;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;
    import android.app.*;
    import android.os.*;
    import android.widget.TextView;

    public class MyTestDemo extends Activity
    {
    private static final String NAMESPACE=”http://tempuri.org/”;
    private static final String URL=”http://localhost:2195/MyWebService/Service.asmx”;
    private static final String SOAP_ACTION=”http://tempuri.org/CelsiusToFahrenheit”;
    private static final String METHOD_NAME=”CelsiusToFahrenheit”;
    TextView tv;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tv=(TextView)findViewById(R.id.TextView01);
    try
    {
    SoapObject request=new SoapObject(NAMESPACE,METHOD_NAME);
    //String xmlString=”jk”;
    request.addProperty(“Celsius”,”5″);

    SoapSerializationEnvelope soapenvelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
    soapenvelope.dotNet=true;
    soapenvelope.setOutputSoapObject(request);
    HttpTransportSE aht=new HttpTransportSE(URL);

    aht.call(SOAP_ACTION, soapenvelope);
    //SoapObject result=(SoapObject)soapenvelope.getResponse();

    // String resultdata=result.getProperty(0).toString();

    //tv.setText(resultdata);
    SoapPrimitive resultRequestSOAP=(SoapPrimitive) soapenvelope.getResponse();
    String str=resultRequestSOAP.toString();
    tv.setText(str.toString());
    //tv.setText(resultRequestSOAP.toString());

    //java.lang.String receivedString=(String)soapenvelope.getResponse();
    //tv.setText(receivedString);
    }
    catch(Exception ex)
    {
    ex.fillInStackTrace();
    }

    }

    }

  36. Here Webservice code..

    using System;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Xml.Linq;

    [WebService(Namespace = “http://tempuri.org/”)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service : System.Web.Services.WebService
    {
    public Service ()
    {

    //Uncomment the following line if using designed components
    //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld(string name)
    {
    return name;
    }
    [WebMethod]
    public int CelsiusToFahrenheit(int Celsius)
    {
    return ((((Celsius) * 9) / 5) + 32);
    }

    }

  37. Hi Prashant !

    How can create set up file of webservice in android application.
    Regards
    Bvenkat Jeewesh

  38. Thanks Prashant !
    I have solved Problem. But In Java, How can create setup file of webservice in Android Application.
    Your’s sincerely
    Bvenkat Jeewesh

  39. Voula says:

    Hello Prashant,
    i have stuck with that problem many days.
    In my android app i have one TabHost with two tabs.
    At the first tab, call a function (Public Function GetNearbyVideo() As Videos()) from webservice and at
    the second tab call the (Public Function PutFile()) function from webservice.
    But whene i change through tabs when i push the second tab it called first the GetNearbyVideo() function and then the PutFile() function
    but i want called only the PutFile() function.
    I dont know what to do.
    Maybe there is a problem with activities? Must stop the activity in each tab?
    Please help me if you know something about that!
    Thanks a lot

  40. hongdong says:

    hi~
    im korean man
    i have a big problem with android… so i searched your webpage by google..

    i’d like to make some program that can login on webpage like facebook. user should firm form to login on webpage. after that user can see the webpage…

    could you understand..?? my english skill is terrible..i know…kk if you have time to answer my question. plz email to me…thx

    • hongdong says:

      i dont know how i can make program…TT where should i chage on your source…TT

    • Prashant says:

      Hello Hongdong,
      actually in this example i have tries to access the serverside pages, through the android.
      but if you are trying to do some bigger application, then you should better to access web-service.

  41. Stavan says:

    Thaks a lot. Nicely explained.

  42. She says:

    Hi Prashant,
    I just appointed as soft eng..i’ve studied for computer science 6 years back.after completed d studies i neva worked in programming field.. i lost touch with programming. since i joined in soft field everything looks new for me..i was given 2 months time to complete the web portal for one of my department. Im blur, dont know where to start Please advice.

    • Prashant says:

      Hello She,
      I am also a student only, going to complete post-graduation this month. According to me, you should google about the portal webs functionalities.
      Then after getting some idea, design your portal web requirement,
      Side by side, you have to learn the language and their given technologies so that you can write the design in any language.
      There are mainly 3 languages on top now, Java,PHP and .net. Select one of the technology and google all the required resources and tutorials for it.
      Then once the design is over, make a approval. once it is approved, go for database design and implementation.
      Then I think you can begin with writing code for your portal site.

  43. R. Praveen Kumar says:

    Hi Prashant,

    Thanks a lot for this example.. I tried running this..

    url i used is “http://10.0.2.2:8080/webapplication/servletpath”

    but the result is coming as full html text with HTTP status code 500… i done with the same servlet u have done and that servlet executes perfectly when i request through jsp page.. but in emulator it prints that html document with 500 as status code.. i use netbeans for deploying servlets in Glassfish 3.0 server and i use eclipse for android app in 2.2 platform… i need help.. pls reply as soon as possible..

  44. R. Praveen Kumar says:

    Hi Prashant… i found the mistake with the help of glassfish server log.. it said NullPointerException.. the reason is i used parameter names as different in

    postParameters.add(new BasicNameValuePair(“uname”, uname.getText().toString())); statement…. Anyway million thanks for this example… 🙂

    • Prashant says:

      Hi Praveen,
      Thats great. otherwise i might be breaking my head just like dat.. 🙂
      you are always welcome..

  45. psrdotcom says:

    Hi,

    Thank you very much for sharing the info. with source code. It helped me a lot.

  46. Flip says:

    Hey Prashant,

    I tried it out but it doesnt work. What about hidden fields, dont you have to send them also? Because in my case there are hidden fields. I want to login on affili.net. Could you may give me a hint how to go on? 🙂

    Best regards from Germany!

    • Prashant says:

      Hello Flip,
      Thank you. Actually for hidden field, you have to set the value in the post parameter only.
      If you will see in “LoginLayout.java”, in 36 and 37 lines I am adding parameters
      for server request. Just like that, you have to add the hidden field value.

      • Flip says:

        Hey,

        thanks for your answer. Of course I did it but it doesnt work 😦

        I dont know how to make a post that look like that I got when I used HTTPLiveHeader:

        http://www.affili.net/de/desktopdefault.aspx

        POST /de/desktopdefault.aspx HTTP/1.1
        Host: http://www.affili.net
        User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0
        Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
        Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
        Accept-Encoding: gzip, deflate
        Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
        Connection: keep-alive
        Referer: http://www.affili.net/de/Startseite.aspx
        Cookie: __utma=63082623.645886804.1309014041.1310731656.1310814225.8; __utmz=63082623.1310814225.8.5.utmcsr=publisher.affili.net|utmccn=(referral)|utmcmd=referral|utmcct=/Start/default.aspx; ASP.NET_SessionId=h3dn1c45nbyf5nedcaxpsaqr; __utmc=63082623; __utmb=63082623.1.10.1310814225
        Content-Type: multipart/form-data; boundary=—————————179402113612065
        Content-Length: 1128
        —————————–179402113612065
        Content-Disposition: form-data; name=”__EVENTTARGET”

        —————————–179402113612065
        Content-Disposition: form-data; name=”__EVENTARGUMENT”

        —————————–179402113612065
        Content-Disposition: form-data; name=”__VIEWSTATE”

        /wEPDwULLTIwNjQyNTkxMzMPZBYCAgQPZBYEZg9kFgJmD2QWAmYPZBYCAgIPZBYKAggPDxYCHgRUZXh0BQpVc2VyIExvZ2luZGQCCg8PFgIfAAUIUGFzc3dvcnRkZAIQDw8WAh8ABQJHT2RkAhIPFgIfAAUFTG9naW5kAhQPDxYEHwAFE1Bhc3N3b3J0IHZlcmdlc3Nlbj8eC05hdmlnYXRlVXJsBSF+L2RlL2Rlc2t0b3BkZWZhdWx0LmFzcHgvdGFiaWQtODhkZAICDw8WAh4HVmlzaWJsZWhkZGQ=
        —————————–179402113612065
        Content-Disposition: form-data; name=”pathinfo”

        /tabid-9/rewritten-1/
        —————————–179402113612065
        Content-Disposition: form-data; name=”ctl00$ctl03$txtLogin”

        514838
        —————————–179402113612065
        Content-Disposition: form-data; name=”ctl00$ctl03$txtPassword”

        stuyE8e4
        —————————–179402113612065
        Content-Disposition: form-data; name=”ctl00$ctl03$lnkLogin”

        GO
        —————————–179402113612065–

        HTTP/1.1 302 Found
        Date: Sat, 16 Jul 2011 11:04:15 GMT
        Server: Microsoft-IIS/6.0
        X-Powered-By: ASP.NET
        X-AspNet-Version: 2.0.50727
        Location: https://publisher.affili.net/login/login.aspx?theValue=xgFNAK7ufqbJtA4johDyiCyNASgf4OIv2Mhs19B4FdB50g%3d%3d
        Cache-Control: private
        Content-Type: text/html; charset=utf-8
        Content-Length: 224

      • Prashant says:

        Did you convert result to the plain text?

  47. Aditya says:

    Hello !
    while working on andriod app i got stuck on blocking incoming call using my appp could anyone of you help.

  48. Jugal Desai says:

    dude i like ur work…
    i need a help
    i have a web site http://www.vidyalankarlive.com
    how can i connect login to it…

  49. Jugal Desai says:

    i am getting exceptions during run time…in the login text box…

    java.lang.illegalStateException host must not be null or set etc…

    • Prashant says:

      at line no. 41 of LoginLayout.java, we have to give the url of the php page(according to your server), which will be requested from android.
      We will serve the posted data to the same page, and that php page will take care of the posted data and send response to the android.

  50. Jugal Desai says:

    response = CustomHttpClient.executeHttpPost(“http://www.vidyalankarlive.com/site/content/”, postParameters);

    ya i did this right…and even if i give correct password it says incorrect…

  51. Jugal Desai says:

    the problem is that it is not showing the page name…did u check the website by urself?

    • Prashant says:

      Yes I checked. Actually for android login, in the webserver, you have to upload a new php page that will receive the posted data from the android and send response as 0 or 1 (plain text).
      now the same page URL you have to provide for the parameter.

  52. Jugal Desai says:

    i tried ../login.php ../loginpage.php
    but same thing worng password…

  53. Jugal Desai says:

    ohh okie thanx..so instead of that 0 or 1 i can also use the text which it already sends me back and change in my android app instead of changing it in my college web site right…

    • Prashant says:

      Yes, the two application(android and web) will access different page, but same database.

      • Jugal Desai says:

        hmm okie…i can talk with the guy who created that website…
        actually i am planning to create an app which will be like Facebook…
        our college hosts server where every1 can chat n do such other stuffz. it is also designed by past students only…
        so i need a help on it…

      • Prashant says:

        Okay, you can create such kind of application. This example, i have posted which i have implemented for my final sem live project.
        After that project, now I am back to J2EE.
        For your project, I would like to suggest you to go threw web-services. After implementing the web-service, development of the DB related application will be more easier.

  54. Jugal Desai says:

    can u suggest me somthing??

  55. Jugal Desai says:

    ya thanx…but i tried many things but not able to login into our college web site…even tried with facebook…
    but again redirecting to the login page…
    i displayed the contents of ur ‘res’ variable into a file…and i saw that it contained the login HTML code…

  56. asha says:

    I want to develop an application that contains login page in that we have to enter our facebook login id and password ,if it is correct it will send to us to another class(may photo capturing or another activity).what i mean is when i press login ,the login id and password i have given will check with facebook id and password if it exist we can enter in to other activity.Dont go to facebook page.is it possible?

    • Prashant says:

      Hello asha,
      As you are talking about the facebook login, it means you want to use their database.
      It will be possible if facebook is providing you any API or Web-Service.
      I have found such login in TuneWiki application on android but dont know how they had implemented it.

  57. Jugal Desai says:

    I tried to connect to a local hosted web-site php and i am getting an exception

    response = CustomHttpClient.executeHttpPost(“http://localhost/xampp/vit/checklogin.php”, postParameters);

    org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused

    i am using XAMPP to host a local host…and which i am using browser to login there is no problem…

    mainlogin.php is the html form for login in php
    and checklogin.php is where i check the login details are correct or not…

    checklogin.php

    • Prashant says:

      Hello Jugal,
      use IP address instead of localhost, ie 127.0.0.1. It will work.

      • Jugal Desai says:

        but same error…org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused

      • Jugal Desai says:

        i solved the problem…instead of localhost i used my lan ip address…
        i went searching and found out that if we write localhost or 127.0.0.1 in the emulator it uses the localhost of the emulator and not when we are hosting from pc using apache,tomcat,etc.
        So i changed it to

        response = CustomHttpClient.executeHttpPost(“http://169.254.10.1/xampp/vit/checklogin.php”, postParameters);

      • Prashant says:

        That is gud, I thought you were using in stand alone PC so I told default IP address 127.0.0.1.

  58. PPai says:

    HI Prashant,
    I am new to android, I am trying the login application, but when i try to get the response from the php it returns me html code thus it shows invalid login message. I tried debugging and found that it return status message “access denied”, i was trying to give credentials but still not succeeded . can you please help me?

  59. ES says:

    Hi Prashant, es here, I’m new to android and now i want to make a simple login which got username and password. On your last coding part, which is Server-side, may I know where should I put the coding?

  60. ES says:

    Sorry for disturbing Prashant, I still having Login with this error : “java.lang.IllegalArgumentException: Illegal character in scheme at index 0: ” when I try for login on adroid emulator. Your helped will be appreciate.

    • Prashant says:

      can you please check, when you click on the login button what parameter are posting to the server page and what respond it is sending to the android.

  61. yostane says:

    Hi, thanks for the article.
    Is it better to encrypt form params to enhance security or not?

    • Prashant says:

      Actually, when you are sending the data by post, it will send encrypted only. So i think, encryption is not so important.

  62. james says:

    do i download a server all the other code seem to have no error but i just don know where to place the last code would you please explain and thank you so much for your help.

    • Prashant says:

      Hello James,
      Last code is for server side, which should be placed into your web-server. In this case, i have placed into the java webserver, Apache Tomcat.
      The android application will make request to this page url with the given parameter.

  63. Hossam says:

    Hi Prashant ,
    Great thanks for this excellent example
    Hossam.

  64. Hossam says:

    Hi Prashant i did the application but i get user name and password from database but i don’n know , it always say uncorrect user name or password .But the with static information it work.

    here is my code.

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com;

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
    *
    * @author Hossam
    */
    @WebServlet(name = “AndroidResponse”, urlPatterns = {“/AndroidResponse”})
    public class AndroidResponse extends HttpServlet {

    Vector v1 = new Vector();
    Vector vCheck;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    String un, pw;
    un = request.getParameter(“username”);
    pw = request.getParameter(“password”);
    try {
    Class.forName(“com.mysql.jdbc.Driver”);
    String url = “jdbc:mysql://localhost:8080/bank”;
    Connection con = DriverManager.getConnection(url, “root”, “3344”);
    Statement select = con.createStatement();
    ResultSet rs = select.executeQuery(“select USERNAME,PASSWORD from user_info”);

    while (rs.next() == true) {
    Vector v = new Vector();
    v.add(rs.getString(“USERNAME”));
    v.add(rs.getString(“PASSWORD”));
    v1.add(v);
    }
    } catch (SQLException ex) {
    Logger.getLogger(AndroidResponse.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
    Logger.getLogger(AndroidResponse.class.getName()).log(Level.SEVERE, null, ex);
    }

    // if (un.equalsIgnoreCase(“hossam”) && pw.equals(“123”)) {
    // out.print(1);
    // } else {
    // out.print(0);
    // }

    for (int i = 0; i < v1.size(); i++) {
    vCheck = (Vector) v1.get(i);
    String userName = vCheck.elementAt(0).toString();
    String password = vCheck.elementAt(1).toString();
    if (un.equalsIgnoreCase(userName) && pw.equals(password)) {
    out.print(1);
    } else {
    out.print(0);
    }
    }
    }

    /**
    * Returns a short description of the servlet.
    * @return a String containing servlet description
    */
    @Override
    public String getServletInfo() {
    return "Short description";
    }//
    }

    • Prashant says:

      This servlet code.. once please check in browser, by passing the parameter by query-string(url). then check whether its printing 1/0
      and ha.. go to view source and check whether it is printing only test only not html. I think after u check this.. I can clearly give you solution.

  65. vineet says:

    hey thanx a lot buddy … this is the code i was looking for …. god bless people like u 🙂

  66. dilli says:

    hi prashanth my name is dilli,
    while am running this project am getting “the application has stopped unexpectedly.please try again”

  67. dilli says:

    can u solve this please

  68. dilli says:

    package com.example.login;

    import java.util.ArrayList;

    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    public class LoginLayout extends Activity {
    EditText un,pw;
    TextView error;
    Button ok;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    un=(EditText)findViewById(R.id.et_un);
    pw=(EditText)findViewById(R.id.et_pw);
    ok=(Button)findViewById(R.id.btn_login);
    error=(TextView)findViewById(R.id.tv_error);

    ok.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
    // TODO Auto-generated method stub

    ArrayList postParameters = new ArrayList();
    postParameters.add(new BasicNameValuePair(“username”, un.getText().toString()));
    postParameters.add(new BasicNameValuePair(“password”, pw.getText().toString()));

    String response = null;
    try {
    response = CustomHttpClient.executeHttpPost(“Http://72.15.221.151”, postParameters);
    String res=response.toString();
    res= res.replaceAll(“\\s+”,””);
    if(res.equals(“1”))
    error.setText(“Correct Username or Password”);
    else
    error.setText(“Sorry!! Incorrect Username or Password”);
    } catch (Exception e) {
    un.setText(e.toString());
    }

    }
    });
    }
    }

  69. dilli says:

    package com.example.login;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.URI;
    import java.util.ArrayList;

    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.params.ConnManagerParams;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;

    public class CustomHttpClient {
    /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
    * Get our single instance of our HttpClient object.
    *
    * @return an HttpClient object with connection parameters set
    */
    private static HttpClient getHttpClient() {
    if (mHttpClient == null) {
    mHttpClient = new DefaultHttpClient();
    final HttpParams params = mHttpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
    ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }
    return mHttpClient;
    }

    /**
    * Performs an HTTP Post request to the specified url with the
    * specified parameters.
    *
    * @param url The web address to post the request to
    * @param postParameters The parameters to send via the request
    * @return The result of the request
    * @throws Exception
    */
    public static String executeHttpPost(String url, ArrayList postParameters) throws Exception {
    BufferedReader in = null;
    try {
    HttpClient client = getHttpClient();
    HttpPost request = new HttpPost(url);
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
    request.setEntity(formEntity);
    HttpResponse response = client.execute(request);
    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer sb = new StringBuffer(“”);
    String line = “”;
    String NL = System.getProperty(“line.separator”);
    while ((line = in.readLine()) != null) {
    sb.append(line + NL);
    }
    in.close();

    String result = sb.toString();
    return result;
    }finally{
    if (in != null) {
    try {
    in.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }

    /**
    * Performs an HTTP GET request to the specified url.
    *
    * @param url The web address to post the request to
    * @return The result of the request
    * @throws Exception
    */
    public static String executeHttpGet(String url) throws Exception {
    BufferedReader in = null;
    try {
    HttpClient client = getHttpClient();
    HttpGet request = new HttpGet();
    request.setURI(new URI(url));
    HttpResponse response = client.execute(request);
    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer sb = new StringBuffer(“”);
    String line = “”;
    String NL = System.getProperty(“line.separator”);
    while ((line = in.readLine()) != null) {
    sb.append(line + NL);
    }
    in.close();

    String result = sb.toString();
    return result;
    } finally {
    if (in != null) {
    try {
    in.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }

  70. dilli says:

    here am sending the full coding please find this and inform me whats the mistake i did

    • Prashant says:

      first of all tell me that, when are you getting the error, at the loading of the application or on the click event of the button?

  71. dilli says:

    i am getting this error on loading time

    • Prashant says:

      I have sent you the source project of this example into your email. Please check it out and change according to your requirement.
      and in this project, the URL will be the server side page URL which will handle the login.

  72. dilli says:

    thanks prashanth am new to the android thanks alot

  73. dilli says:

    and more doubt you how to develop the dashboard in android

  74. dilli says:

    one more doudt you know how to develop dashboard in android

  75. dilli says:

    thanks again u helped me a lot

  76. dilli says:

    prasanth again am gettin the same error when am running that application

  77. dilli says:

    for that program i enter the ip address am not getting that

  78. dilli says:

    72.15.221.151 this ip am using

  79. dilli says:

    hi prasanth
    Actually i have to develop a program like its log in page already user name and pass word is stored in our company server and database is sql server

  80. dilli says:

    please give me a solution

  81. ES says:

    Hi Prashant, can you email me your success login code with php??? Actually I just want to do a login page which after user insert their username and password and then go through the database(mysql) to check wheter correct or not, and if its correct then the android will show ‘Login Success’. Please help me ><"

  82. dilli says:

    Hi ,Prashanth we r using sql server,and server program we r using asp.net please help me

    • Prashant says:

      Hello Dilli,
      In asp.net, check the user and print either 1 in login succeed or 0 in login fail. And dont forget to send response in plain text format (Page.Response.ContentType = “text/plain”).

  83. harish says:

    Hi,
    How to do Login authentication in android using remote database.

    i have written above code but it’s showing the total data of the url but it’s not taking the particular data to compare how can i do this with specific data i.e. uname and pwd.

    kindly give reply.

    Thanks In advance.

    • Prashant says:

      Hello Harish,
      You have to create a request page, which will get connection from the database then compare received data and print “1” or “0”.
      And don’t forget to response as plain text.

  84. harish says:

    Hi,

    How can we store data in remote database(like MySql) in android.

    Can you help me regarding this.

    Thanks.

    • Prashant says:

      Hi,
      You can go threw my new post, It is all about storing dat only.

      • harish says:

        Hi,

        How to store data in remote database(like MySql) not in SQLite(Local database).

        Thanks.

      • Prashant says:

        Send all the value as parameter and in serverside, receive the posted data and insert into the database.
        Print 1 or 0, recordset result which will received by the android as a confirmation of the insertion.

  85. prabhu says:

    plz tel how to connect and hit the server to retrieve user name and password from webserver,not retrieve through database

    • Prashant says:

      The serverside code you are writing in Java, ASP or PHP. In those page only you can make a connection to the database and retrieve.

  86. harish says:

    Hi,

    In the above post where you are comparing the values i.e. username and password.

    kindly reply me.

    Thanks.

    • Prashant says:

      You can see the last code(AndroidResponse class) of the post is for getting the value from the android and sending the response.

  87. Aruljothi says:

    Hi Prsanth…

    Ur article is very nice… I’m new to android programming…
    I would like to develop android apps…i need ur help….can u explain the login code for me

    • Prashant says:

      Hi Arunjothi..
      In login, I am just accepting the posted data from the android and after that comparing the received data, I ll be printing “1” or “0” according to condition.

  88. Thang says:

    Hi, Prashant
    Thank you very much for you tutorial. I’m new in Android programming. I’ve read your example. But it doesn’t work for me. I’m writing an application need do the flowing:
    1. Login to PHP server with username and password.
    2. If success, start an activity to upload image.
    But, my problem is i can’t write my own AndroidResponse and then upload to server because the server is belong to other people, i can’t access their server. Second, i have tried some code to login website, one of them is:
    public boolean doLogin(String username, String password) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 15000);
    try {
    HttpGet httpget = new HttpGet(“http://www.tamtay.vn/”);

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();

    System.out.println(“Login form get: ” + response.getStatusLine());
    entity.consumeContent();

    System.out.println(“Initial set of cookies:”);
    List cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
    System.out.println(“None”);
    } else {
    for (int i = 0; i < cookies.size(); i++) {
    System.out.println("- " + cookies.get(i).toString());
    }
    }

    HttpPost httpost = new HttpPost("http://ids.tamtay.vn/user/login&quot;);

    List nvps = new ArrayList ();
    nvps.add(new BasicNameValuePair(“username”, “username”));
    nvps.add(new BasicNameValuePair(“password”, “password”));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    response = httpclient.execute(httpost);
    entity = response.getEntity();
    System.out.println(“Login form get: ” + response.getStatusLine());
    entity.consumeContent();

    System.out.println(“Post logon cookies:”);
    cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
    System.out.println(“None”);
    } else {
    for (int i = 0; i < cookies.size(); i++) {
    System.out.println("- " + cookies.get(i).toString());
    }
    }

    if (response.getStatusLine().getStatusCode() == 200) {
    return true;
    } else {
    return false;
    }
    } finally {
    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
    }
    }

    The problem is in some website, with any value of username and password, the sever always response with status code 200. And in website i need to login, in about 4, 5 time login first, the server reponse with status code 401, and then always 200. Can you tell me the reason? Thank you, Thank you very much. Actually, i'm very confused. Sorry about my English.

  89. vinay says:

    hi prasanth,

    im doing a project where in a single screen i should be able to enter name,enter contact no,enter emailid,enter other info,take some photos,record audio.finally i should send a mail with attached photos and audio files in Zipped format. can u please help.

    thanks
    vinay

  90. CHR says:

    Hi i have an application(struts) running on server(Tomcat) and i sent a request from my android Http client program then server responded with a html output.Then how can i prepare a GUI screen using the data i.e received in response.For connecting to more resource of Web Server.

    • Prashant says:

      While the response can be sent as normal text form right? Instead of normal response, send pain text response from the application.

  91. vinay says:

    thank you

  92. pradeepraj says:

    In CustomHttpClient.java
    the below method.. to get the Http Get reply from the Servlet class have never been called from the android app
    public static String executeHttpGet(String url) throws Exception

    I cant follow this working part technically and i searched this too . .

    Request token is fired to Servlet with executeHttpPost(url,parameter)

    Servlet replied for it thru print Stream

    after that how without calling executeHttpGet(url) we could get reply from the servlet..

    I was a beginner .. so dont mistake about the questions.. little bit in detail will provide me some assistance

    • Prashant says:

      Hello Pradeepraj,
      Actually GET and POST are the method to send the request to the database with given parameter.
      Here in this example I have used post method, so I have called executeHttpPost() method.
      Now the parameter will be sent to the server using any of these method and as response,
      it will get the compiled output of the URL. It may be in the form of text, XML or JSON.

  93. hi i am a newbie in android dev could someone kindly email me this project kindly. twinkioko@gmail.com

  94. JakubG says:

    Hey

    I plan to create a Android apps to login in with a login and password stored in MySQL and i try to use your very good code but i have some problem. Can u halp me with php part – i have a file with connect to localhost database – i will send u a file php ok ??

  95. harish says:

    Hi Prashant,

    Now as a response from server i’m getting total feed i need specific data i.e. sessionId from that feed how can i get it.(If my data i.e. Username and pwd is wrong then i’m getting response as invalid details).

    thanks

    • Prashant says:

      Send your response as plain text instead of HTML output.

      • harish says:

        The server is at remote place i can’t edit it from server i’ll get the data as follows

        lt data gt
        lt uname gt xyz lt&\ uname gt
        lt pwd gt abcbyv lt\ pwd gt
        lt sessionid gt 12345asdf789 lt\ sessionid gt
        lt \data gt

        From the above i need to retrieve sessionId how can i do it.

      • Prashant says:

        can you send me the serverside code, so that I can confirm, why you are getting such response.

  96. myCuestion says:

    I read all comment but i don’t know where create my servlet

    my tree is:

    login
    src
    com.example.login
    CustomHttpClient.java
    LoginLayout.java
    gen
    com.example.login
    R.java
    android.jar
    assets
    res
    drawable-hdpi
    drawable-ldpi
    drawable-mdpi
    layout
    main.xml
    values
    strings.xml
    AndroidManifest.xml
    default.properties
    proguard.cfg

  97. Rajat Pandey says:

    hiiii prashant!!!!!!
    i m getting this response on my android emulator
    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):
    My JSP ‘index.jsp’ starting page

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333): <!–
    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333): –>

    10-23 02:36:58.121: INFO/LOG Response(333):
    10-23 02:36:58.121: INFO/LOG Response(333):
    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):
    This is my JSP page.
    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    plz.. help me out prashant!!!!!!

  98. Rajat Pandey says:

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):
    My JSP ‘index.jsp’ starting page

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333): <!–
    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333): –>

    10-23 02:36:58.121: INFO/LOG Response(333):
    10-23 02:36:58.121: INFO/LOG Response(333):
    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):
    This is my JSP page.
    10-23 02:36:58.121: INFO/LOG Response(333):

    10-23 02:36:58.121: INFO/LOG Response(333):

    This is the response i m getting
    plz help me outbcoz o m new to servlet

  99. Kandie Kip says:

    Hi,
    Thanks for the code.
    I have tried the using the same code and I fell into a problem dealing with android.os.NetworkOnMainThreadException. If you have any idea about this problem I would highly appreciate.
    I am using Android 3.2.
    Regards.

  100. ratnayake says:

    i am developing user login with getting data from WCF/Json service. my userlogin function returns Boolean value as a result .
    i need to consume WCF.json service by passing parameters from Android and get the response . .

    call WCF/Json service is done. if any one can please help me how to get the response ..

  101. Nilay says:

    Hi,

    I am also new to Android. I have done this login part and now I want to know about the maintaining sessions(using cookies etc,). Can you please give me some guidance about how to go forward. If you can send me some sample code, it will be very helpful.

    Regards
    Nilay

  102. srikanth says:

    Super…I am fine of you..Good job

  103. Hi Prashant,

    I’m trying to use this example you gave, but it’s not working for me.

    I need to send Username and password by clicking on a button that sends both data to this url: http://stats.serhstourism.com/?U=USUARI&K=PASSWORD
    I understand for it that I have to use GET method, isn’t it? but every time I want to connect it doesn’t works.
    What should I do?

    thanks!

  104. mahi says:

    hi, i am new to android. Where we write serverside code.

  105. stathis says:

    Hi Prashant,
    Great tutorial!!!But i have a question.
    Can we use this application to login in our gmail account? Or at least something similar?
    Could you post an example?

  106. velu says:

    hi prashanth, very useful code for new android developers. but small application where i want write that package.com code. please reply me…

  107. Meghanad says:

    Hi Prasanth,
    I am new to Android i have a doubt about drawable…. I am trying to store images in only drawable-hdpi the images are stretching automatically in XML File…..I dot know how to solve this can u help me……..Thanks

  108. Ryein says:

    Great example

  109. krishnaveni says:

    Hi dis is useful tutorials…thanks…..

  110. lisha says:

    thanks a lot…
    But can you tell me what the jsp page you wrote is??/
    or did you write the servlet…..
    i am totally confused…
    please do help me….

  111. shyam says:

    Hello,

    I am new to android development. Can you please explain me “what is ‘clicklistener’ ? “

  112. Nirmal says:

    hey im getting error in importing the:

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    i have made seperate “web.com” package in same project for AndroidResponse class..is it true..??

  113. Nirmal says:

    please help me…….

  114. siri says:

    Hi…
    I am new to android development.I’m trying to use this example you gave, but it’s not working for me. I entered username and password and click login button output is not displayed.

    • Prashant says:

      Please once print the response to the log file. once you will come to know the response, it will be easier to fix.

  115. Riadh says:

    Prashant hello:
    Thank you for this tutorial, please if you can help me I’m working on a small project android JEE and I want to know how to send a notification of my application JEE to Android

    • Prashant says:

      In a certain interval of time, you can send request to the server to check whether there is any notification or not.
      If it is there, you should get it as response.

  116. Himg says:

    u have given example of servlet,i m doing it with jsp page…
    out.print is sending null to android..plzz helppp

    • Prashant says:

      Hello Himg, I have tested it with JSP also.
      It was worked. please once test your code with URL.
      then later you can access with android.

  117. Himanshu says:

    is this tutorial for 2.2.X ?

  118. Vivek elangovan says:

    Hi prasanth,
    i tried ur sample the build part is completed and it is working fine.now i need to know where to create AndroidResponse.java and also where to specify the urls

    • Vivek elangovan says:

      hi prasanth,
      i created that servlet but still i m getting incorrect username and password.what may be the problem?

      • Prashant says:

        Have you trimmed the blank spaced?
        Once just print and check what response you are getting from server.

        Thank you.

    • Prashant says:

      Actually you have to upload the ndroidResponse.java to the web-server.
      and you have to give the same url of the server file.

  119. Gowthami says:

    Hey Prashant! Nice tutorial! I was wondering if you can use this code with Google App Engine. If there are any changes to this code with Google App Engine, can you provide it for us?

  120. krishnaveni says:

    Hi Good Evening…
    am successfully done ur above example…now i need its redirect to next page..the next activity having ur(login user) firstname and lastname fetched from database…..how it is do????plz help me friends….thanks in advance. am used one coding part…

    here more number of admin user(ajay,krish,hari) loged means all r firstname and lastname displayed…but i need who r loged(ajay) in the login page that user(ajay) details only displayed …so give me some solutions for me…thanks in advance….

  121. Raj says:

    Thanks for the article. It is really good. I’m new to android programming.

    I didn’t understand the server-side. what should I do in order to execute your code??? I have tomcat installed on my system.

    Please do help me with the steps about how to get the server-side working.

  122. gaurav says:

    Hi Prashant,
    I am very beginner in android programming i need know where i have to save AndroidResponse .java i read all the comment u told we have save webserver (where is this and how to do ) in eclipse file-> new->java project or android project i am not getting ( can u take screen shot of where / how to do like this ) actually i am first time doing like this.
    thanks in advance

  123. gaurav says:

    and why u hv written (package=”com.example.layout”) in manifest.xml package is (com.example.login) i am not getting this one also.

  124. gaurav says:

    and 1 more question would i need to connect tomcat pls send me details of step by step execution, also u can send this id ddelhisingh@gmail.com

  125. Sweaty says:

    Hi…
    i am new in android, can u tell me how to use the last servlet file? means where to paste it.
    i am very confused….
    kindly send me your personal mail address too.
    Thankssss

  126. krishnaveni says:

    hi….thanks for ur rly…i already done pass data between intent.(ie)username is passed and displayed next activity.but i need Dis is my database:

    username password firstname lastname

    krishnaveni xxxxx krish veeman

    hariprasad xxxxx hari prasad

    arirajaguru xxxxxx raja ari

    Now my login form am entered krishnaveni and password entered means its successfully logged then move to next activity.that next activity having logged person (krishnaveni) firstname(krish) and lastname(veeman) only displayed fetched from database…Loged person hariprasad means hariprasad firstname(hari) and lastname(prasad) only displayed…
    dis is my php file :
    0)
    {

    echo 0;
    }
    else
    {
    echo 1;

    }
    ?>
    how it is do in android……itz fetched from database…plz give me some solutions…thanks in advance..

  127. Omnya says:

    hi ,
    it’s very impressive efforts
    but I’ve a problem ,, I created all android classes and the servlet page also but when I runned it the emulator’s output is an exception,, I think that the problem is that the andriod code couldn’t now the place of my sevlet ,, can you help me 🙂 ??

  128. krishnaveni says:

    Hi….how is connecting mysql database using jdbc…

  129. Haresh says:

    Hey Prashant…..Good Work Yaar…

    Can you help me here…My problem has similarity with your post….

    What if I use a php file instead of Servlet….in php..we use apache server…and i have problem when i give the target URL like

    http://localhost/haresh/check.php

    please tell me what’s the exact way to access the webservice which is placed on your local PC itself with a apache server

  130. Ok, I have been trying to use this code with a md5 hashed password.. I am using the code from…

    http://evolt.org/node/60384

    But I’m having problems trying to incorporate the two.

    Any ideas?

    Thanks!

  131. mido says:

    hi Prashant
    first thank you for your code ,i get an exception name android.os.NetworkOnMainThreadException and what i understand that we must do the call to the web server in single thread but i don’t know what to do , can you help me
    thanks in advance

  132. karthik says:

    hi prashant,
    can u write a sample just to print a string on a jsp page and that string i send it from android phone.im using a local host(tomcat server).pls help me . im new to android.

  133. gopi says:

    Hi Prashath , love to see you helping so many new learning guys . i need one help too 🙂 first of all i want you to please give some info on which web server you used for your app and how to configure the same. and also in my case i want to access some information kept in database of server , please tel me how can i implement it .Please give your email id if you wish ..thanks my email id is : gopinath0123@gmail.com

    • Prashant says:

      Hello Gopi,
      Here is a video tutorial to install apache tomcat.

      I hope this may help you to install web-server.
      and then after you can be able to run Java Servlet into your sysytem.

      And to communicate with the server, you can send data as post, as I have done in this example.
      and you can retrieve info from server, as this example only. Here I have retrive 1 or 0,
      instead of that you can retrieve your string. And if the data is set of rows and column,
      you can access the string in a group seperated by a special character(~,$,^ etc) and later you can
      use StringTokenizer to seperate it.

  134. gopi says:

    Hi Prashanth ,

    Could you please tel me which webserver you used and also tell me where i need to paste your last program of servlet in the webserver please..thanks a lot

    • gopi says:

      hi prashanth , i have installed apache tomcat sever but am not able to understand where exactly i have keep the servlet program of yours server and also need to know any configuration needs to be done …plz help me as this servlet thing is new to me…

  135. ani says:

    hey prashant!! im trying to make n android app for my col where i want to implement d student login lage of col website .. so wat i want is if d user inputs all d details in my android app interface all dose login details will be fed to d col website’s loggin page internally n d user will get all all d information from d loggin page.. dis is d link of d webpage dat i want to implemnt https://webkiosk.jiit.ac.in/.. im new to android ,, pls help me..plllls ill be highly gr8ful to u if u help u out pllls…

    • Prashant says:

      Hello Anisha,
      without the database information (db-host, uesername and password) you will not able to access the college database.
      and if you can get those info, you can create a web-service or use my above example to access the database using the JSP or servlet code.

  136. vametata says:

    Thanks for this code……..

  137. Monti says:

    Hey Prashant i want to use this log in page to access an already existing log in page , how can i do that ? please help..

    • Prashant says:

      Hello Monti,
      you will have to create a new jsp/servlet page for only accessing the database. And you can retrieve or insert data by communicating with the page from android.

      • Monti says:

        Hi Prashant ,
        thanks for your reply , is there some tutorial that i can follow in order to achieve this step ?!

  138. saranya says:

    sir !
    i got org.apache exception
    what will i do
    tell me sir

    • Prashant says:

      hi saranya…
      first of all, plz.. I am not sir. I am just a learner like you.

      and about the exception, are you running it in localhost-webserver?
      if yes please use it with the ip address instead of loalhost.

  139. ram481987 says:

    hi

    can u please tell me where(folder) exactly i should place AndroidResponse file .

    Thanks in advance………………:-)

  140. abhinav says:

    hey prashant its great help , i am very new at android development .. i just tried your code it say…..
    ok.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub

    “Multiple markers at this line
    – The method onClick(View) of type new View.OnClickListener(){} must override a superclass
    method
    – implements android.view.View.OnClickListener.onClick”

    ??

  141. abhinav says:

    hi again ,
    I removed the 1st error and then pasted my url in the line 41 of the code
    but when i run the code in the emulator i get an error java.lang.illegalStateexception :traget host mush not be null , or set in parameters ..
    scheme=null, host=null , path=……………………………….
    can u help me with this .. it would be great to hear from you soon .. thanks a lot

    • Prashant says:

      What is the URL, for which you are making request from the android?

      • abhinav says:

        https://dashboard.actionside.com/login
        i just want to make a login screen in the app .. through which i can post my id and password ..
        to the following site .. and i am not able to get how to do it .. it would be great if you can help me in that .. you can email the code to me ..
        thanks a lot for the reply ,hope to hear from you soon ..

    • Monti says:

      hi abhinav , i am preparing an application very similar to yours i would really appreciate it of you tell me how did you accomplish posting username and password info to the webpage you mentioned…
      thanks

      • abhinav says:

        monti .. i would definitely tell u how i did it .. but rite now i have some idea but it is not working fine , so as soon as i get the ans. i will try to mail u or post here , no prob .. till then have a good search 🙂

      • Monti says:

        ok this is my email :aftermath.89@hotmail.com
        thanks 🙂

  142. pinkie says:

    Hi Prashant, thanks for explanation and code… Having some doubts-
    web server can be tomcat server in which the servlet is kept right?
    Also can it be executed from the emulator giving the corresponding URL like
    http://localhost:8080/examples/servlets/servlet/FirstApp….?

  143. srikanta says:

    Thanks for good solution.

  144. Archana says:

    Hi

    I am very thankful to you.

    I need a help i am running the program and its running fine and i am getting error “sorry! Incorrect username and password”

  145. akash says:

    hi can u send me the mobile tracker code

  146. Akiff Bin Kasban says:

    Thanks for the codes! Great job! Is there any way to use this with XML rpc?
    Im new to this , any help would be appreciated .

  147. Nice code, is there any way to connect my jsp page to my android application, means i want to send a link from my jsp page to my application, please help. THANK YOU

  148. Aneeb says:

    Hey everyone i dont know where to place the server-side coding???? Can anyone help me??
    i am new to this..

  149. The last part means servlet part is not working.
    I am getting error in import javax.servlet.annotation. Web Servlet;
    and another is @WebServlet(name=”AndroidResponse”, urlPatterns={“/androidres.do”}) this portion.please help me.
    Thanks in advance……

  150. Hi….
    I resolving the error by installed the servlet jar file.
    But I am not getting the right result.
    When i m entering the login and password.
    It is showing the some illegal. Java. target exception.
    Please help me……

    Thanks in advance………..

  151. song young hun says:

    it is goog code but i have a problem

    i can get response from server but the response has html tag

    but i think you don’t have html tag…

    i wanna get only number 1 or 0 like you

    how should i do to solve this problem

  152. hanu says:

    hi prashant could please help me how we can download the image from server using json.

  153. I m trying ,but i don’t know how will create servlet page????????plz help me……..

    • chulmoveon says:

      Hello Gyanendra,,
      If you like, you can try paste the code to JSP too. Just copy-paste the contain of doPost function. I have try that, and it works 😉 I just don’t know why (Im a new in Java)
      Please, maybe other can explain?

    • chulmoveon says:

      Hello Gyanendra, If you like to, you can just copy-paste the conteny of doPost (without import declaration) to a JSP page. I have try that, and it works 😉
      I still dont know why, but please maybe other can answer how it can work well also in JSP?

  154. Abhinai says:

    hi i have a problem with this annotation at line 6
    import javax.servlet.annotation.WebServlet; and the error is The import javax.servlet.annotation cannot be resolved
    i have imported the annotations-api.jar file but the error remains same
    and at line 15 @WebServlet(name=”AndroidResponse”, urlPatterns={“/androidres.do”})
    error is The attribute name is undefined for the annotation type WebServlet
    – WebServlet cannot be resolved to a type
    – The attribute urlPatterns is undefined for the annotation type WebServlet

  155. Amit says:

    Hi Prashant, Thanks for the code as it helped me to understand httpClient server programming.
    But my actual problem is that I want my application to connect to a web-server having url:- http://109.169.49.24/mobiletracker and get username and password authenticated. But I am facing problem. Please help me as I am new to Android and I am not getting any solution.

  156. Monti says:

    Hey amit i am working on the same concept with a different web page you need o track the communication between your browser and the webserver using firebug for Firefox for example , and see how the browser sends the parameters username and password , and you have to replicate the request using android code , this is is what i have done till now but i am stuck with sending cookies to the webserver if your page doesn’t deal with cookies then it should work just fine , good luck

  157. AMIT says:

    Hey Monti , actually I am not using the browser. In my android application there is a login page where I enter username and password & on the press of login button it goes to server url (mentioned above) and both details gets authenticated and my appliaction is connected to the server. Now when I fetch my location it displays on my device as well as on the server web-page. My problem is that I am unable to connect my application with the server & just failing how to connect it properly. If you have any idea please help me.

    • Monti says:

      Yes Amit i know what you meant , what i was talking about is the browser on PC , you should open the webpage on Firefox or internet explorer and use an http monitor to see how the communication with the webpage is made , then you can make copies of these requests in android, send your email and i will tell you more details if you want,,,

  158. irfan khan says:

    how i can create service in android i am new for android

    irfan khan

  159. irfan khan says:

    can you show a programm to create a notification generate on broadcast reciever to changed wallpaper

  160. Pingback: Login Check in Server Side | PHP Developer Resource

  161. Shrey says:

    hi
    i used the same code but when i run it there is an error saying
    the process has stopped unexpectedly.
    Please help.

  162. Loveb says:

    Hi,Prashant Good Post, but i have make change as per my requirement changes are as below:
    Servlet name changed to TestWebServlet.java
    Annotation changed to @WebServlet(name=”TestWebServlet”, urlPatterns={“/TestWebServlet”})
    in the LoginDemoActivity.java at line no 41 i have given Url is “http://127.0.0.1:9090/Test/TestWebServlet” and also try with ip of my system.
    But when i call from Android phone i am getting connection refused ….

  163. Loveb says:

    Can u please help me for the my problem??

  164. andy says:

    Hi prashanth
    I was trying to execute u r code but its showing error in simulator that android.os.NetworkOnMainThreadException am trying to run 4.0.3 version and found that and also i try to run in 2.1 and 2.3 but it is asking this application api 15 and not launching .I want to know this application atleastr compatible with version after 2.1 .And am the first developer in my company i got a project to convert the institute website into mobile application i started work with your tutorial for login page please give me solution for the errors because i am working in out of india so i cant even take help from my friends

  165. andy says:

    yes i did but its not working

  166. Shivam saxena says:

    Servlet class on server not working. I gave doPost() method . in this method —-

    PrintWriter out= response.getWriter();
    out.println(“hi i am here”);
    Statement stmt=null;
    Connection con=null;
    String name= request.getParameter(“name”);
    String registration=request.getParameter(“registration”);
    String method= request.getParameter(“value”);
    String value=request.getParameter(“reg”);

    String insert_query=”insert into demo(NAME,REGISTRATION) Values(‘”+name+”‘,'”+registration+”‘)”;
    String select_query=”select * from demo where REGISTRATION='”+value+”‘”;

    try
    {
    Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);
    Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);
    con= DriverManager.getConnection(“database connection link”,”username”,”password”);
    }catch(Exception e)
    {
    out.println(“The exception is “+e.getMessage());
    }

    switch(Integer.valueOf(method))
    {
    case 0:
    {
    try {
    stmt= con.createStatement();
    int i= stmt.executeUpdate(insert_query);
    out.println(“”+i);

    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    out.println(“SQLEXCEPTION-1 “+e.getMessage());
    }

    break;
    }
    case 1:
    {
    ResultSet set;
    try {
    set = stmt.executeQuery(select_query);
    set.next();
    while(set.next())
    {
    try
    {
    JSONObject obj= new JSONObject();
    obj.put(“name”,set.getString(“name”));
    obj.put(“registration”, set.getString(“registration”));
    out.println(set.getString(“name”));
    out.println(set.getString(“registration”));
    out.print(obj);
    out.print(set.getString(“name”));
    out.print(set.getString(“registration”));
    }catch(Exception e)
    {
    out.println(“Json Exception “+e.getMessage());
    }
    }
    } catch (SQLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    out.println(“SQLEXCEPTION-2 “+e1.getMessage());
    }

    }
    }

    when i send data through NameValuePair then value stored in database but store out.println(“”+i); statement not work.

  167. Sandeep Reddy says:

    ThanQ

  168. nikhil says:

    hey prashant where to put servlet file …
    i am running my android app with netbeans and i store my servlet file in netbeans only ..
    whenever i press login button in my app it every time gives error that login is incorrect so what to do…
    even if i used correct username and password so please help me…

    • Prashant says:

      you can tost the response your are receiving from server. And you can check what result you are getting.

  169. Jia says:

    Hi..
    I want to develop an application that contains login page in that we have to enter our Moodle (http://download.moodle.org/windows/) login id and password, if it is correct it will login, the login id and password i have given will check with moodle id and password if it exist we can enter. I want to use the open source moodle database. Moodle is providing Soap and Rest Web-Services also. I want to create Moodle API and Android Application. I will be glad if you help me a bit. Please guide me

    • Prashant says:

      Hello Jia,
      You can use web service(is best option) or use the same same concept I have used in my application.
      Looking at your site, it must be in PHP. the according to above example you will have to replace
      the servlet with PHP code.

      • Jia says:

        Really glad to receive your reply 🙂
        Yup, Moodle is in PHP. I’ve used the same same concept as you, just replacing the try block as follows:

        try { response = CustomHttpClient.executeHttpPost(“http://10.0.2.2/mymoodle/server/moodle/login/token.php?username=username&password=password&service=moodle_mobile_app”, postParameters);
        String res = response.toString();
        err.setText(res); }

        but when I click the login button on emulator, it responds back in an error:
        “error”:”ununsupported redirect detected, script execution terminated”
        whereas when I open the same URL i.e.
        http://localhost/mymoodle/server/moodle/login/token.php?username=username&password=password&service=moodle_mobile_app
        in browser, it returns a token as it should.
        Please help.
        Regards,
        Take Care..

      • Prashant says:

        can you send me the token.php code?

      • Jia says:

        This is token.php:

        <?php
        // This file is part of Moodle – http://moodle.org/
        //
        // Moodle is free software: you can redistribute it and/or modify
        // it under the terms of the GNU General Public License as published by
        // the Free Software Foundation, either version 3 of the License, or
        // (at your option) any later version.
        //
        // Moodle is distributed in the hope that it will be useful,
        // but WITHOUT ANY WARRANTY; without even the implied warranty of
        // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
        // GNU General Public License for more details.
        //
        // You should have received a copy of the GNU General Public License
        // along with Moodle. If not, see .

        /**
        * Return token
        * @package moodlecore
        * @copyright 2011 Dongsheng Cai
        * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
        */

        define(‘AJAX_SCRIPT’, true);
        define(‘NO_MOODLE_COOKIES’, true);

        require_once(dirname(dirname(__FILE__)) . ‘/config.php’);

        $username = required_param(‘username’, PARAM_USERNAME);
        $password = required_param(‘password’, PARAM_RAW);
        $serviceshortname = required_param(‘service’, PARAM_ALPHANUMEXT);

        echo $OUTPUT->header();

        if (!$CFG->enablewebservices) {
        throw new moodle_exception(‘enablewsdescription’, ‘webservice’);
        }
        $username = trim(textlib::strtolower($username));
        if (is_restored_user($username)) {
        throw new moodle_exception(‘restoredaccountresetpassword’, ‘webservice’);
        }
        $user = authenticate_user_login($username, $password);
        if (!empty($user)) {

        //Non admin can not authenticate if maintenance mode
        $hassiteconfig = has_capability(‘moodle/site:config’, get_context_instance(CONTEXT_SYSTEM), $user);
        if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
        throw new moodle_exception(‘sitemaintenance’, ‘admin’);
        }

        if (isguestuser($user)) {
        throw new moodle_exception(‘noguest’);
        }
        if (empty($user->confirmed)) {
        throw new moodle_exception(‘usernotconfirmed’, ‘moodle’, ”, $user->username);
        }
        // check credential expiry
        $userauth = get_auth_plugin($user->auth);
        if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
        $days2expire = $userauth->password_expire($user->username);
        if (intval($days2expire) get_record(‘external_services’, array(‘shortname’ => $serviceshortname, ‘enabled’ => 1));
        if (empty($service)) {
        // will throw exception if no token found
        throw new moodle_exception(‘servicenotavailable’, ‘webservice’);
        }

        //check if there is any required system capability
        if ($service->requiredcapability and !has_capability($service->requiredcapability, get_context_instance(CONTEXT_SYSTEM), $user)) {
        throw new moodle_exception(‘missingrequiredcapability’, ‘webservice’, ”, $service->requiredcapability);
        }

        //specific checks related to user restricted service
        if ($service->restrictedusers) {
        $authoriseduser = $DB->get_record(‘external_services_users’,
        array(‘externalserviceid’ => $service->id, ‘userid’ => $user->id));

        if (empty($authoriseduser)) {
        throw new moodle_exception(‘usernotallowed’, ‘webservice’, ”, $serviceshortname);
        }

        if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
        throw new moodle_exception(‘invalidiptoken’, ‘webservice’);
        }
        }

        //Check if a token has already been created for this user and this service
        //Note: this could be an admin created or an user created token.
        // It does not really matter we take the first one that is valid.
        $tokenssql = “SELECT t.id, t.sid, t.token, t.validuntil, t.iprestriction
        FROM {external_tokens} t
        WHERE t.userid = ? AND t.externalserviceid = ? AND t.tokentype = ?
        ORDER BY t.timecreated ASC”;
        $tokens = $DB->get_records_sql($tokenssql, array($user->id, $service->id, EXTERNAL_TOKEN_PERMANENT));

        //A bit of sanity checks
        foreach ($tokens as $key=>$token) {

        /// Checks related to a specific token. (script execution continue)
        $unsettoken = false;
        //if sid is set then there must be a valid associated session no matter the token type
        if (!empty($token->sid)) {
        $session = session_get_instance();
        if (!$session->session_exists($token->sid)){
        //this token will never be valid anymore, delete it
        $DB->delete_records(‘external_tokens’, array(‘sid’=>$token->sid));
        $unsettoken = true;
        }
        }

        //remove token if no valid anymore
        //Also delete this wrong token (similar logic to the web service servers
        // /webservice/lib.php/webservice_server::authenticate_by_token())
        if (!empty($token->validuntil) and $token->validuntil delete_records(‘external_tokens’, array(‘token’=>$token->token, ‘tokentype’=> EXTERNAL_TOKEN_PERMANENT));
        $unsettoken = true;
        }

        // remove token if its ip not in whitelist
        if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
        $unsettoken = true;
        }

        if ($unsettoken) {
        unset($tokens[$key]);
        }
        }

        // if some valid tokens exist then use the most recent
        if (count($tokens) > 0) {
        $token = array_pop($tokens);
        } else {
        if ( ($serviceshortname == MOODLE_OFFICIAL_MOBILE_SERVICE and has_capability(‘moodle/webservice:createmobiletoken’, get_system_context()))
        //Note: automatically token generation is not available to admin (they must create a token manually)
        or (!is_siteadmin($user) && has_capability(‘moodle/webservice:createtoken’, get_system_context()))) {
        // if service doesn’t exist, dml will throw exception
        $service_record = $DB->get_record(‘external_services’, array(‘shortname’=>$serviceshortname, ‘enabled’=>1), ‘*’, MUST_EXIST);
        // create a new token
        $token = new stdClass;
        $token->token = md5(uniqid(rand(), 1));
        $token->userid = $user->id;
        $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
        $token->contextid = get_context_instance(CONTEXT_SYSTEM)->id;
        $token->creatorid = $user->id;
        $token->timecreated = time();
        $token->externalserviceid = $service_record->id;
        $tokenid = $DB->insert_record(‘external_tokens’, $token);
        add_to_log(SITEID, ‘webservice’, get_string(‘createtokenforuserauto’, ‘webservice’), ” , ‘User ID: ‘ . $user->id);
        $token->id = $tokenid;
        } else {
        throw new moodle_exception(‘cannotcreatetoken’, ‘webservice’, ”, $serviceshortname);
        }
        }

        // log token access
        $DB->set_field(‘external_tokens’, ‘lastaccess’, time(), array(‘id’=>$token->id));

        add_to_log(SITEID, ‘webservice’, ‘user request webservice token’, ” , ‘User ID: ‘ . $user->id);

        $usertoken = new stdClass;
        $usertoken->token = $token->token;
        echo json_encode($usertoken);
        } else {
        throw new moodle_exception(‘usernamenotfound’, ‘moodle’);
        }

      • Prashant says:

        okay, just once do not echo that header and try.

      • Jia says:

        The same error pops up 😦

      • Prashant says:

        Then please once Toast what response you are getting from server.

      • Jia says:

        Response:
        “error”:”ununsupported redirect detected, script execution terminated”

  170. Hey Prashant. I am new to Android development. I have taken an assignment to create an app for a website. I am trying to write code for login. I have the following problems:

    1) I do not know how to implement a servlet code. (Please help me out)

    2) When I connect my android phone and run the app it gives me an error saying – wrong username/password.

    3) On my emulator, I am getting an error saying – android.os.NetworkOnMainThreadException.

    Can you guess what the problem is? Any help would be very much welcome. Thanks in advance. 🙂

  171. hi prashant,
    I am facing the problem.
    Here is my android code…
    ……………………………………….

    package com.example.login;

    import java.util.ArrayList;

    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class LoginLayoutActivity extends Activity {
    EditText uname,password;
    TextView error;
    Button ok;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    uname=(EditText)findViewById(R.id.et_un);
    password=(EditText)findViewById(R.id.et_pw);
    ok=(Button)findViewById(R.id.btn_login);
    error=(TextView)findViewById(R.id.tv_error);

    ok.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
    // TODO Auto-generated method stub

    ArrayList postParameters = new ArrayList();
    postParameters.add(new BasicNameValuePair(“uname”, uname.getText().toString()));
    postParameters.add(new BasicNameValuePair(“password”, password.getText().toString()));

    String response = null;
    try {
    response = CustomHttpClient.executeHttpPost(“http://127.0.0.1:8080/Login/login1.AndroidResponse”, postParameters);
    String res=response.toString();
    Toast.makeText(getApplicationContext(),”Response:”+res,Toast.LENGTH_LONG).show();
    res= res.replaceAll(“\\s+”,””);
    if(res.equals(“1”))
    error.setText(“Correct Username or Password”);
    else{
    error.setText(“Sorry!! Incorrect Username or Password”);
    // Toast.makeText(getApplicationContext(),”Response:”+res,Toast.LENGTH_LONG).show();
    }

    } catch (Exception e) {
    uname.setText(e.toString());
    }

    }
    });
    }
    }
    ……………………………………….
    here is my servlet code.
    ………………………………………….
    package login1;

    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    @WebServlet(name=”AndroidResponse”, urlPatterns={“/AndroidResponse”})
    public class AndroidResponse extends HttpServlet {

    /**
    *
    */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType(“text/plain”);
    PrintWriter out=response.getWriter();
    String un,pw;
    un=request.getParameter(“uname”);
    pw=request.getParameter(“password”);
    if(un.equalsIgnoreCase(“prashant”) && pw.equals(“sharma”))
    out.print(1);
    else
    out.print(0);
    out.println(“”);
    out.println(“”);
    out.println(“Hello World!”);
    out.println(“”);
    out.println(“”);
    out.println(“Hello World!”);
    out.println(“”);
    out.println(“”);
    }
    }
    ……………………………………………………………………..
    I use the Tomcat server 7.
    I am not use web.xml in my servlet project because of @WebServlet(name=”AndroidResponse”, urlPatterns={“/AndroidResponse”}).
    I use the url http://127.0.0.1:8080/Login/login1.AndroidResponse.
    I use the localhost server.

    Now I am facing the problem in servlet code.
    I see the servlet code with brower in eclipse.
    url is http://127.0.0.1:8080/Login/login1.AndroidResponse.
    but I can not see the “HelloWorld”
    I insert the Internet permission in android Manifest.

    if you have any idea.please help me………….
    I am waiting for your reply because I need your help.

  172. hi prashant ,
    I want to connect my android emulator and web server .
    I use this code .
    but I get the url error.
    please help me.

  173. hlaingwintun says:

    hi Prashant,
    I used IP address instead of localhost(127.0.0.1).
    I used above code which is I post last day!
    But i get the error connection refuse.
    I want you to test this above code.I want your email address.
    Please Help me.

  174. Oshada says:

    Thank U for your great code..But there is a problem for me.

    I put this servlet under “D:\myproject\apache-tomcat-7.0.29\webapps\hello\WEB-INF\classes” directory. is it OK??

    Then what should be my URL for line no 41 in LoginLayout.java file. I currently use this as URL “http://10.0.2.2:8080/hello/response”..am I wrong?? Please tell me how to get this URL correctly..

    When I run my project with above details it always gives as “wrong Username and password” 😦

  175. hlaingwintun says:

    Hi prashant,
    I had already used this IP(127.0.0.1) in my application.
    I also used the IP(10.0.2.2)
    I post the code on above comment.
    But I get the error connection refuse.
    How to solve the problem.
    Please help me.

  176. Hi,Can you sent your project to me?
    hlaingwintunn@gmail.com

  177. kushagra says:

    hi,i have made code for login where there is login and user name . but when i try to connect to local host(wamp server).i am not clear that where should i put the php code in wamp.actually when i login in emulator my app crashes it shows force like that

    • kushagra says:

      actually i am converting my college website into mobile application so i have to authenticete the user name amd password from college server but initially i have made local wamp server my eclipse code is showing user name and password but when i try to enter sumit my password and code my emulator stops .(i am using php for the access in local server….)

      • Prashant says:

        it seems you are not getting the URL for the path for the server.. please try with the ip address.

      • haddad riadh says:

        hello prashant thank you ,please helpe me ,i would like to create native application like this

        2012/9/1 Prashant’s Blog

        > ** > Prashant commented: “it seems you are not getting the URL for the path > for the server.. please try with the ip address.” >

      • Prashant says:

        So how can I help you riadh?

    • Prashant says:

      actually you will have to put the site as a basic web-site, i think httpdocs in wamp.
      and then you have to give the post or get url in source code as http://127.0.0.1:portno/site.

  178. gokul tk says:

    hi prashant i m new to android application developing have basic knowledge about java…. i need to develop one application that covers end to end application,,, that should make use of client,,, server,,, and fetch data from mysql… please tell code u have written is enough to perform this operation

  179. sachin says:

    in my eclipse there is an error in import javax……. statements
    my eclipse cant read javax package
    so, what should i do
    sachin

  180. prabhat says:

    Hello Prabhat,

    i am new in android where can i put my server url in this code.. i dint understang for the login.
    it meance i have created page on the server with name and password field,
    whr will be put of this url for registering and login…

  181. Baljai says:

    Hello Prashant,, I did all the steps as above, but am getting “unfortunately loginactivity has stopped” when i click on loginactivity application. Do we have any logs to trace the exception & problem?

  182. venky says:

    hi sir this is my eeror in db

    10-01 13:27:01.079: E/AndroidRuntime(530): android.database.sqlite.SQLiteException: no such column: usrname: , while compiling: SELECT fname, sname, usrname, email, pass, cpass, phno FROM user

    • Prashant says:

      Please execute the query into the sql-editor first. then it will be easier for you to identify the sql problem.

  183. hello sir, I find your article so useful for my application but the problem is I don’t know how to deal with the mysql. I’ll be using joomla integrated with xammp for a local server as well as a database.

    • Prashant says:

      create a php page to communicate with datebase. then you can communicate the newly created php
      from android interface.

  184. Jia says:

    Hey Prashant,
    Can you help me with the logout code for your application given above, please??

    • Prashant says:

      Hello Jia,
      Just write the Session destroy code into a servlet/jsp then call it from android interface.
      If the call result one, redirect to the login interface.

  185. Kelvin says:

    where will I put the servlet?and whatkind of file is it?

  186. Charmie says:

    I want to have the login page code along with its database connectivity code. I mean the querries which will insert my data into the database and can make any modifications accordingly.

    Reply soon

    Thanking you
    Charmie

  187. mikee says:

    Hi Prashant , I’m new in Android Programming. Is there any detailed tutorial you can give to me so I can follow and understand your tutorial. I just want to learn this. I don’t have any idea where to start.

  188. Hmm is anyone else experiencing problems with the pictures on this blog loading?
    I’m trying to find out if its a problem on my end or if it’s the blog.

    Any feedback would be greatly appreciated.

  189. suresh says:

    hi prasant thanks for this nice code but i got error android.os.net work on main thread.plz reply

  190. hi i am new in android, i have implemented ur above code with some changing according to my criteria, in my app m getting Latitude, longitude from GPS, display in Gmap, and then send to the web server, here is my android code code, CustomHttpClient is same as you wrote..

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    parameter = new ArrayList();

    mapView = (MapView) findViewById(R.id.themap);
    mapView.setBuiltInZoomControls(true);
    final MapController controller = mapView.getController();
    Toast.makeText(MainActivity.this, “Google Map is displaying”,
    Toast.LENGTH_LONG).show();
    controller.setZoom(12);

    LocationManager locationManager = (LocationManager) this
    .getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager
    .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    double longitude = location.getLongitude();
    double latitude = location.getLatitude();
    GeoPoint point = new GeoPoint(
    (int) (longitude *1e6),
    (int) (latitude *1e6));
    controller.setCenter(point);
    controller.animateTo(point);
    parameter.add(new BasicNameValuePair(“Longitude”, Integer.toString(1234)));
    parameter.add(new BasicNameValuePair(“Latitude”, Integer.toString(5678)));
    SendData(parameter);
    String message = “Longitude = ” + longitude + ” Latitude = ” + latitude;

    Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    LocationListener locationListner = new LocationListener() {

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    String message = “GPS status changing\n”;
    Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onProviderEnabled(String arg0) {
    String message = “GPS is Enabling\n”;
    Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onProviderDisabled(String arg0) {
    String message = “GPS is Disabling\n”;
    Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLocationChanged(Location arg0) {

    double longitude = arg0.getLongitude();
    double latitude = arg0.getLatitude();
    GeoPoint point = new GeoPoint(
    (int) (longitude *1e6),
    (int) (latitude *1e6));
    controller.setCenter(point);
    controller.animateTo(point);

    String message = “Location Changed to Longitude = ” + arg0.getLongitude() + ” Latitude = ” + arg0.getLatitude();
    Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();

    parameter.add(new BasicNameValuePair(“Longitude”, Integer.toString(point.getLongitudeE6())));
    parameter.add(new BasicNameValuePair(“Latitude”, Integer.toString(point.getLatitudeE6())));
    SendData(parameter);

    }
    };

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListner);
    }

    public void SendData(ArrayList params){
    String response = null;

    try {
    response = CustomHttpClient.executeHttpPost(“http://localhost:8080/myApp/”, params);
    String res = response.toString();

    res = res.replaceAll(“\\s+”,””);
    if(res.equals(“0”)){
    Toast.makeText(getBaseContext(), “Error in data transfor”, Toast.LENGTH_LONG).show();
    }
    if(res.equals(“1”)){
    Toast.makeText(getBaseContext(), “Received”, Toast.LENGTH_LONG).show();
    }
    }
    catch (Exception e) {
    Toast.makeText(getBaseContext(), “Communication with server failed”, Toast.LENGTH_LONG).show();
    }

    }

    —————————————–>> server code is <<——————————–
    @WebServlet(name = "AndroidServlet", urlPatterns = {"/androidres.do"})
    public class AndroidServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    System.out.println("Post here");

    PrintWriter out = null;
    String longitude, latitude;

    while (true) {
    try {
    out = response.getWriter();
    longitude = request.getParameter("Longitude");
    latitude = request.getParameter("Latitude");
    out.println("”);
    out.println(“”);
    out.println(“Servlet NewServlet”);
    out.println(“”);
    out.println(“”);
    out.println(“Servlet NewServlet at ” + longitude + “, ” + latitude + “”);
    out.println(“”);
    out.println(“”);
    out.println(“1”);
    } finally {
    out.println(“0”);
    out.close();
    }
    }
    }
    }

  191. Namita says:

    hey prashant,
    i’m using a web layout which loads jsp page with javascripts..and the problem is it is showing the output with those scripts when i’m running the program.
    can you help me plz.

  192. kettu says:

    How and where I can build AndroidResponse.java in android ?

  193. eazy1337 says:

    Hello

    Thank you for a very nice tutorial.

    I have a bug in my code and I don’t know how to fix it, I have located it at this line:
    HttpResponse response = client.execute(request);

    Why doesn’t this line work? What are the possible fixes?

    Thanks

  194. shubhm says:

    while setting android internet permission in manifest.xml file
    i got some error like yellow triangle @line and while running the same code posted of login..
    when i run my emulator i get error like Unfortunately appname has stopped

    The error in console
    An established connection was aborted by the software in your host machine

    i m not getting what should i do then.

  195. Mika says:

    Thank you very much !!!! I’m working on that since 3 days and I’was blocked on syntax code but all is very clear now ! Thanks a lot

  196. priti says:

    Hi,,,im getting an error like btn_ok cannot be resolved or it is not a field…..in all these lines
    (setContentView(R.layout.main);
    un=(EditText)findViewById(R.id.et_un);
    pw=(EditText)findViewById(R.id.et_pw);
    ok=(Button)findViewById(R.id.btn_ok);
    error=(TextView)findViewById(R.id.tv_error);……………………..)

    wer i need to correct….wer i shd check in main.xml layout…etc

  197. Mayaa says:

    looks good… this site http://androidtechstuffs.blogspot.in/2013/01/login-application-for-android.html also provides good example… Have a look!!

  198. kailesh ahir says:

    i want to make login activity in which user shoud enter username and password,it will check for response and give apropriate message and if login is correct than make session management for holle application.please give me fast solustion as source code.thank you in advance.

  199. kailesh ahir says:

    where to write servlet file and and user name and password is dynamically change,give me solution.

  200. “Login Application For Android Prashant’s Blog” truly got myself simply hooked on your blog! I reallydefinitely will be back alot more regularly. Thanks ,Francis

  201. Shubhanshu says:

    Hi, nice eg but i am getting an error in the layout in the “java.lang.IllegalArgumentException name may not be null” in the username edittext after clicking the login button though i am passing both username and password . I have followed the same steps as you said. Any help would be appreciated.

  202. charitha amarasinghe says:

    one of great tutorial, thanx a lot.
    a kindly request,
    can you make a android tutorial for input data like listview selected items sending to server side.

  203. ryann says:

    i have the java , manifest ad android part done but have no idea how to add the servlet part . can u please help with directions, just specifying upload to webservices doesnt help at all, i tried search engine but got no answer cleard. please help with the steps or procedure . it would be of great help . thanks

  204. Nkm2.Org says:

    What a information of un-ambiguity and preserveness of valuable familiarity concerning unpredicted feelings.

  205. Dee says:

    Thank u sooo much.. i can very well run my project with the help of your snippet!

  206. seema says:

    i tried the above code but still I am not able to login.can any one tell me how to get it done.I am getting invalid login

  207. venkatesh says:

    In the code you are using name value pair as generics but u not at all created the class as name value pair .I’m facing compile error in declaring arraylist

  208. healthy oils says:

    Have you ever experienced how uncomfortable it is
    to have dry skin that flakes and itches and is just too rough to the touch.
    Jojoba mimics the sebum found naturally in human skin and
    can replenish skin that has become dry due to age, weather, environmental pollutants or stresses.
    I have been using jojoba oil for months and love the stuff.

  209. Dillon says:

    Greetings! I know this is somewhat off topic but I was
    wondering if you knew where I could get a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having problems
    finding one? Thanks a lot!

  210. David says:

    Having a problem with an issue someone posted in January, but no response was given yet. Could you provide some assistance?

    Cannot compile and run project do to errors in the following code:

    (setContentView(R.layout.main);
    un=(EditText)findViewById(R.id.et_un);
    pw=(EditText)findViewById(R.id.et_pw);
    ok=(Button)findViewById(R.id.btn_ok);
    error=(TextView)findViewById(R.id.tv_error);

    This is the script provided in the LoginLayout.java file. Error says it cannot be resolved or is not a field

  211. Pingback: Construye una pantalla de login en android | Aprende

  212. Iona says:

    I’m extremely pleased to discover this great site. I want to to thank you for your time just for this wonderful read!! I definitely savored every little bit of it and i also have you book-marked to see new information on your web site.

  213. Lee Wright says:

    I visited this blog it is nice and very informative for apps developers. Thanks for sharing this information

  214. Melina says:

    Great post.

  215. sx says:

    very nice tutorial !
    but in my case , the server i am using is ASP.net . so where and how should i write the servlet code in the web server ?

  216. bhargav says:

    sir i need a android app code which has only username n password to open the app n no server connections..thanks pls reply as soon as possible…

  217. Pingback: dot net página que comprueba los datos de acceso enviados a través de una aplicación android | Foro ASP!

  218. Pingback: dot net page which checks the Login details sent through an android application | QueryPost.com

  219. devesh says:

    can anyone please tell me how to use intent in this code.

  220. Tauseef says:

    m getting error in —- un.setText(e.toString()); // un cannot resolve
    ok.setOnClickListener(new View.OnClickListener() // ok cannot resolve

  221. I tend not to drop many responses, however
    I looked at a few of the responses on Login Application For Android
    | Prashant’s Blog. I actually do have a few questions for you if it’s allright.
    Could it be only me or do a few of these comments appear as if they
    are coming from brain dead individuals? 😛 And,
    if you are writing at other sites, I’d like to keep up with you.
    Could you post a list of the complete urls of your social
    networking sites like your twitter feed, Facebook page or linkedin profile?

  222. Tej Prakash says:

    sir,
    need help, i m new in android. i need an

    Android application
    —————————
    Create one sample application.

    Server side application
    ———————
    Create one button in the page. On click of this button phone should ring.

  223. Biswajit says:

    How can connect to a remote server like QC to get data from there..?

  224. Pramod kumar sinh says:

    hello sir my servlet is responding evry time zero

  225. satya says:

    while using the above code i got exception android.os.networkonmainthreadexception.

  226. saurabh says:

    hi..
    Bro, I’m getting this text in username editbox — android.os.network.OnmainThreadException..pls hep

  227. ramaraodesai says:

    Hi, Prashant, i need help with jsonparsing and login ,register, verify account, and reset password in my android app. i need to contact you on the above job. my emal is rrdesai64@gmail.com. are you interested?

  228. prashant says:

    plz prashant send me simple android project…
    its urgent bro…

    prashantj557@gmail.com

  229. Abhishek says:

    It gives me error as “android.os.networkonmainthreadexception”

  230. ramonacushing says:

    Accounting software when designed for a particular industry offers more custom features specifically targeted to capture the needs. Everything is moving to the digital world and businesses must keep up. This hampers the successful accomplishment of the project.

  231. Vikrant Khullar says:

    hi,
    Where is the customhttpclient added??? Saved as a file and uploaded on the server? But there is no link to the file on the server. Or in the app as a different java class file? how is this class connected then?

    • Vikrant Khullar says:

      Also, how Do I connect to the server table where the username and passwords are connected?
      Please help.. thank you in advance.

    • Prashant says:

      Hi Vikrant,
      Have you notice urlPatterns, that is for creating url. and for validation, I am not using any database.
      if you see if(un.equalsIgnoreCase(“prashant”) && pw.equals(“sharma”)), I have clearly written it is a text comparison.
      but yes, if you want to compare it with database row, you can write code in that way. Thanks.

      • Vikrant Khullar says:

        Also Prashant sorry to keep making you reply I had this problem in creating the servelet.. it says that the “web.com” can not be accepted.. Could you, if possible, tell me like a rookie how to create the servelet.. waiting for your response..

  232. vito82b1093271 says:

    You’re so awesome! I don’t believe I have read something like this before. So nice to discover someone with original thoughts on this topic. Seriously.. many thanks for starting this up. This web site is something that’s needed on the web, someone with some originality!

  233. floy1753245 says:

    Aw, this was an incredibly good post. Taking the time and actual effort to generate a top notch article… but what can I say… I put things off a whole lot and don’t manage to get anything done.

Leave a reply to Rohit Cancel reply