Monday, June 15, 2009

How to use Http connection , SaxParser and SharedPreferences in Android

The following code helps you to create a login screen and connect with the server using the Http connection.
The login url will give the following xml file as a output.
-----------------------------
< login>
      < status> SUCCESS </status>
      < message> Login Successful </message>
</login>
------------------------------

< login>
      < status> ERROR </status>
      < message> Login Failed </message>
</login>
------------------------------
Here im using the saxparser to retreive the xml output.
Application will navigate the user to the welcome page once he logged in successfully.
Otherwise user will get login failed message.
The username and password will be stored in the SharedPreferences after the successful login.
Application will navigate the user to the main page directly once the user completed the login successfully.
User need not to login each time of application launching.

AndroidManifest.xml
--------------------
<?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="login.sample"
      android:versionCode="1"
      android:versionName="1.0.0">
      < uses-permission android:name="android.permission.INTERNET" />
      < application android:icon="@drawable/icon"
            android:label="@string/app_name">
            < activity android:name=".LoginActivity"
            android:label="@string/app_name">
                  < intent-filter>
                        < action android:name="android.intent.action.MAIN" />
                        < category
            android:name="android.intent.category.LAUNCHER"/>
                  </intent-filter>
            </activity>
            < activity android:name=".LoginError"
            android:label="@string/app_name"
            android:theme="@style/Theme.CustomDialog">
                  < intent-filter>
                        < action android:name="android.intent.action.VIEW" />
                        < category android:name="android.intent.category.DEFAULT" />
                  </intent-filter>
            </activity>
            < activity android:name=".Welcome"
            android:label="@string/app_name">
                  < intent-filter>
                        < action android:name="android.intent.action.VIEW" />
                        < category android:name="android.intent.category.DEFAULT" />
                  </intent-filter>
            </activity>
      </application>
</manifest>


main.xml
---------

<?xml version="1.0" encoding="utf-8"?>
< AbsoluteLayout
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      xmlns:android="http://schemas.android.com/apk/res/android" >

      < Button
            android:id="@+id/btn_sign_in"
            android:layout_width="100px"
            android:layout_height="wrap_content"
            android:text="Sign In"
            android:layout_x="103px"
            android:layout_y="197px"/>
      < EditText
            android:id="@+id/txt_username"
            android:layout_width="250px"
            android:layout_height="wrap_content"
            android:hint="Username"
            android:singleLine="true"
            android:textSize="18sp"
            android:layout_x="40px"
            android:layout_y="32px" />
      < EditText
            android:id="@+id/txt_password"
            android:layout_width="250px"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:singleLine="true"
            android:textSize="18sp"
            android:password="true"
            android:layout_x="40px"
            android:layout_y="86px" />
</AbsoluteLayout>

Login Failed message will be displayed in the customized dialog box.

styles.xml
----------

<?xml version="1.0" encoding="UTF-8"?>
< resources>
      < style name="Theme.CustomDialog" parent="android:style/Theme.Dialog">
            < item name="android:windowBackground">@drawable/box</item>
      </style>
</resources>

box.xml
-------

<?xml version="1.0" encoding="UTF-8"?>
< shape xmlns:android="http://schemas.android.com/apk/res/android">
      < solid android:color="#f0600000" />
      < stroke android:width="3dp" color="#ffff8080" />
      < corners android:radius="3dp" />
      < padding android:left="10dp" android:top="10dp" android:right="10dp"
            android:bottom="10dp" />
< /shape>


loginerror.xml
--------------

<?xml version="1.0" encoding="UTF-8"?>
< AbsoluteLayout
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      xmlns:android="http://schemas.android.com/apk/res/android" >
      < TextView
            android:id="@+id/tv"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"/>
      < Button android:id="@+id/btn_ok" android:layout_width="80px"
            android:layout_height="wrap_content" android:text="OK"
            android:layout_x="83px" android:layout_y="60px" />
</AbsoluteLayout>

welcome.xml
-----------
<?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
      < TextView
            android:id="@+id/myEditText"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Welcome, You are Successfully logged in"/>
</LinearLayout>

LoginActivity.java
------------------

package login.sample;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {
      /** Called when the activity is first created. */
      private static final String TAG = "Login";
      Button signin;
      String loginmessage = null;
      Thread t;
      private SharedPreferences mPreferences;
      ProgressDialog dialog;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
            if (!checkLoginInfo()) {
                  signin = (Button) findViewById(R.id.btn_sign_in);
                  signin.setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                              showDialog(0);
                              t=new Thread() {
                                    public void run() {
                                          tryLogin();
                                    }
                              };
                        t.start();
                        }
                  });
            }
            else {
                  /*Directly opens the Welcome page, if the username and password is already available
                  in the SharedPreferences*/
                  Intent intent=new Intent(getApplicationContext(),Welcome.class);
                  startActivity(intent);
                  finish();
            }
      }
      @Override
      protected Dialog onCreateDialog(int id) {
            switch (id) {
                  case 0: {
                        dialog = new ProgressDialog(this);
                        dialog.setMessage("Please wait while connecting...");
                        dialog.setIndeterminate(true);
                        dialog.setCancelable(true);
                        return dialog;
                  }
            }
            return null;
      }
      private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                  String loginmsg=(String)msg.obj;
                  if(loginmsg.equals("SUCCESS")) {
                        removeDialog(0);
                        Intent intent=new Intent(getApplicationContext(),Welcome.class);
                        startActivity(intent);
                        finish();
                  }
            }
      };
      public void tryLogin() {
            Log.v(TAG, "Trying to Login");
            EditText etxt_user = (EditText) findViewById(R.id.txt_username);
            EditText etxt_pass = (EditText) findViewById(R.id.txt_password);
            String username = etxt_user.getText().toString();
            String password = etxt_pass.getText().toString();
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://.......");
            List nvps = new ArrayList();
            nvps.add(new BasicNameValuePair("username", username));
            nvps.add(new BasicNameValuePair("password", password));
            try {
                  UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,
HTTP.UTF_8);
                  httppost.setEntity(p_entity);
                  HttpResponse response = client.execute(httppost);
                  Log.v(TAG, response.getStatusLine().toString());
                  HttpEntity responseEntity = response.getEntity();
                  Log.v(TAG, "Set response to responseEntity");

                  SAXParserFactory spf = SAXParserFactory.newInstance();
                  SAXParser sp = spf.newSAXParser();
                  XMLReader xr = sp.getXMLReader();
                  LoginHandler myLoginHandler = new LoginHandler();
                  xr.setContentHandler(myLoginHandler);
                  xr.parse(retrieveInputStream(responseEntity));
                  ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
                  if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) {
                        // Store the username and password in SharedPreferences after the successful login
                        SharedPreferences.Editor editor=mPreferences.edit();
                        editor.putString("UserName", username);
                        editor.putString("PassWord", password);
                        editor.commit();
                        Message myMessage=new Message();
                        myMessage.obj="SUCCESS";
                        handler.sendMessage(myMessage);
                  } else if(parsedLoginDataSet.getExtractedString().equals("ERROR")) {
                        Intent intent = new Intent(getApplicationContext(), LoginError.class);
                        intent.putExtra("LoginMessage", parsedLoginDataSet.getMessage());
                        startActivity(intent);
                        removeDialog(0);
                  }
            } catch (Exception e)
            {
                  Intent intent = new Intent(getApplicationContext(), LoginError.class);
                  intent.putExtra("LoginMessage", "Unable to login");
                  startActivity(intent);
                  removeDialog(0);
            }
      }
      private InputSource retrieveInputStream(HttpEntity httpEntity) {
            InputSource insrc = null;
            try {
                  insrc = new InputSource(httpEntity.getContent());
            } catch (Exception e) {
            }
            return insrc;
      }
      //Checking whether the username and password has stored already or not
      private final boolean checkLoginInfo() {
            boolean username_set = mPreferences.contains("UserName");
            boolean password_set = mPreferences.contains("PassWord");
            if ( username_set || password_set ) {
                  return true;
            }
            return false;
      }
}



LoginHandler.java
-----------------

package login.sample;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class LoginHandler extends DefaultHandler {
      private boolean login = false;
      private boolean status = false;
      private boolean message = false;
      private ParsedLoginDataSet myParsedLoginDataSet = new ParsedLoginDataSet();
      public ParsedLoginDataSet getParsedLoginData() {
            return this.myParsedLoginDataSet;
      }
      @Override
      public void startDocument() throws SAXException {
            this.myParsedLoginDataSet = new ParsedLoginDataSet();
      }
      @Override
      public void endDocument() throws SAXException {
            // Nothing to do
      }
      @Override
      public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
            if (localName.equals("login")) {
                  this.login = true;
            } else if (localName.equals("status")) {
                  this.status = true;
            } else if (localName.equals("message")) {
                  this.message = true;
            }
      }
      @Override
      public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
            if (localName.equals("login"))
                  this.login = false;
            else if (localName.equals("status"))
                  this.status = false;
            else if (localName.equals("message"))
                  this.message = false;
      }
      @Override
      public void characters(char ch[], int start, int length) {
            if (this.status) {
                  myParsedLoginDataSet.setExtractedString(new String(ch, start,length));
            } else if (this.message) {
                  myParsedLoginDataSet.setMessage(new String(ch, start, length));
            }
      }
}

ParsedLoginDataSet.java
-----------------------

package login.sample;

public class ParsedLoginDataSet {
      private String login = null;
      private String message = null;
      public String getExtractedString() {
            return login;
      }
      public void setExtractedString(String extractedString) {
            this.login = extractedString;
      }
      public void setMessage(String extractedString) {
            this.message = extractedString;
      }
      public String getMessage() {
            return this.message;
      }
}

LoginError.java
---------------

package login.sample;

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

public class LoginError extends Activity {
      Button button;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            System.gc();
            setContentView(R.layout.loginerror);
            TextView textview = (TextView) findViewById(R.id.tv);
            String loginMessage = getIntent().getStringExtra("LoginMessage");
            textview.setText(loginMessage);
            button = (Button) findViewById(R.id.btn_ok);
            button.setOnClickListener(new View.OnClickListener() {
                  public void onClick(View v) {
                        finish();
                  }
            });
      }
}


welcome.java
-------------

package login.sample;

import android.app.Activity;
import android.os.Bundle;

public class Welcome extends Activity{
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            System.gc();
            setContentView(R.layout.welcome);
      }
}

91 comments:

  1. Hi Ramesh,

    This is excellent article. i have implemented it without any little bit confusion. keep post these kind of article. All the best.

    ReplyDelete
  2. Thanks Ramesh,
    i am using this application in my current project with out any errors.
    Plz post another applications if u already done.....

    ReplyDelete
  3. Very nice! It works like a charm.

    Thanks for this awesome article!

    ReplyDelete
  4. How can i logout? Thanks for the tutorial!!

    ReplyDelete
  5. Hi Ramesh,

    Such a nice tutorial provided by you. I have used .net web service and ksoap. So, how can i do that? How can i pass my web service into your code? I have same xml format that you have applied. So help me out from this problem.

    ReplyDelete
  6. Hi Ramesh,

    I'm struggling to get this compiled :( in Eclipse as am Android project.

    Do you by any chance have this as a downloadable project - I'd really appreciate it?

    ReplyDelete
  7. Hey Ramesh, Like 'JMF' I am also having problems with this, I have added some logging ability, and found that there is an error in the XMLParsing, specificaly the line;

    xr.parse(retrieveInputStream(responseEntity));

    Do you or perhaps one of you that have made this work have a work around for this?

    Any help would be most appreciated!

    THANKS! =]

    ReplyDelete
  8. hola a todos.. me podrían ayudar sobre como hacer el servlet que se comunique con esta aplicación android.. por favor ayuda.. soy nuevo en esto

    ReplyDelete
  9. Very nice article. Refered this for HTTP connection related issues. Thanks.

    ReplyDelete
  10. I had issues at the xr.parse line also. I found out the reason behind that was because there was spaces within the URL for me. I got around it by using a Stringbuilder and replacing the spaces with %20 and then requests went in fine.

    Hope that works for you.

    ReplyDelete
  11. hey... very nice article... can u give me an idea abt how can i convert the http to something like a telnet...

    ReplyDelete
  12. Here's how to get this to build in Eclipse.

    1. Remove space between < and tags in XML files.
    2. Create res/drawable; put box.xml there.
    3. loginerror.xml and welcome.xml go under res/layout.
    4. styles.xml goes under res/values.
    5. In LoginActivity.java, change line 117 to
    List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();

    6. Comment out line 11 in that file.

    This should get you really close.

    ReplyDelete
    Replies
    1. Here I've error in this program like --> The application LoginExample has stopped Unexpectedly.Can you give solution for that error

      Delete
  13. Thanks , it works fine with WIFI connection , but doesn't with 3G connection on SFR(france), could some one tell me why, and how to fix this "bug" ?

    ReplyDelete
  14. Actually, I couldn't connect with my asp page.

    This sample project always response "unable to login" message.

    In the asp login process page, do i need to insert something??

    ReplyDelete
  15. I can run this code but unable to login

    ReplyDelete
  16. Hi,
    I could run this program but with always with failed. Can anybody or author give me some suggestion/example of asp file which can able to run this program......
    Please help.....my mail "asma_hosna@yahoo.com"

    ReplyDelete
  17. Latest reviews and news about android phones, free droid app and android mobile


    android phones

    ReplyDelete
  18. Thanks for this nice post. It really helped me to figure out a lot of concepts of Android Programming.

    ReplyDelete
  19. how to parse the response which is in the format
    <{'arg1','arg2','arg3'}|{'arg1','arg2','arg3'}>

    ReplyDelete
  20. i am getting exception saying unable to login, pressing of ok button exits the activity.please help me..i am not able to parse the xml.

    ReplyDelete
  21. I am having same login problem.. is that because I am using newer version of sdk, I am using api 8

    ReplyDelete
  22. i am not able to login..
    can some 1 tell me that what URL put here..
    i am using this connection with Web service..

    ReplyDelete
  23. Nicely done... easily configurable for cookie-session successful outcomes etc. Keep it up :-)

    ReplyDelete
  24. Hi ramesh,
    Very thanks for posting this article , it is very useful for me. thanks a lot.

    It may be very helpful to all beginners like me to get good knowledge.
    I hope you will keep posting articles about android app development.

    I have small requirement that, i need to get current latitude ,longitude values to post a webservice. Can you help me in this with some example code. I written some code using LocationManager.requestLocationUpdates(,,), but it is not giving me any values.
    Please guide me in a right way

    thanks in advance
    pandu
    sathya.sri@gmail.com

    ReplyDelete
  25. Hey ur code is correct almost.
    but when comes to login it is giving login failed error all the time
    will u pls send me correct code??
    my mail id is sj.new23@yahoo.com

    ReplyDelete
  26. and if u have code for how to display data in table format after parsing through xml using SAX parser.. pls send me dat too
    waiting for ur reply

    my mail id is same as previous i.e sj.new23@yahoo.com

    ReplyDelete
  27. hi there..thank you for the tutorial.
    i was successfully run your code but i got one problem with it that is when i replace the line :
    "HttpPost httppost = new HttpPost("http:.....");"

    with my own url, i cannot login. did you know why? i really need a reply for this

    thank you,

    ReplyDelete
  28. Hi.... thanks for the code....

    but am unable to login....
    Msg displayed " Please wait while connecting"
    and then force close....


    if someone knows how to solve this, plz tell me....
    And also what should be the name and password

    -Komal

    ReplyDelete
  29. I read about SAX2 at http://www.saxproject.org/quickstart.html and I think it is worth noting that "...a SAX driver is free to chunk the character data any way it wants, so you cannot count on all of the character data content of an element arriving in a single characters event...".

    I think the sample code that was so kindly provided for Ramesh should be modified by people who are using it so that their code takes into the account the possibility that more than one "characters" event might take place for a single element.

    ReplyDelete
  30. Hi,I am Nazeer and i got a problem in this line --xr.parse(retrieveInputStream(responseEntity));
    then go to exception and it displayed no element found. pls tel me the suggestion.

    ReplyDelete
  31. Hi,

    Thanks for a great tutorial. Important things need to be done before get this tutorial run:

    - must have an enable web-service which returns
    an XML file(with the format above) upon a POST request
    - replace "HttpPost httppost = new HttpPost("http://.......");" with your own URL
    - dont make any Toast inside the second thread (my own exp, got Force close msg)

    Thax again.
    ichen

    ReplyDelete
  32. please specify each and every segment like android manifest.xml and permission settings and main activity class file and other file with screenshots then only we can clearly understand

    ReplyDelete
  33. while logging in getting exception unable to login

    ReplyDelete
  34. while logging im getting unable to login..can u pls update me regarding this

    ReplyDelete
  35. gt8 tuts......... it helped me a lot thank u for this

    ReplyDelete
  36. hi
    is this code works with a distant sever
    by just put the url of the script on this server
    in the http ?

    i need an answer please !!!

    ReplyDelete
  37. ok it's works
    my answer to my question

    ReplyDelete
  38. please send me its project folder that i import in eclipse for run

    ReplyDelete
  39. please send me its project folder that i import in eclipse for run. on emailid--manojksohm@rediffmail.com

    ReplyDelete
  40. any possibility to get the downloaded version of this project? Pls mail to alfredselva@gmail.com if possible.

    Thanks
    Alfred

    ReplyDelete
  41. Hello Thanks for such a details info abt connecting to database.
    But i am new to Android so need more details to run this programme.
    First do i need SAX driver installed for running this application.
    Second Wot shud i put in "HttpPost httppost = new HttpPost("http://.......");" lyk can i put "HttpPost httppost = new HttpPost("http://www.hotmail.com"); or any specific URL.
    Can u pls send me the project at deep.pradh@gmail.com. I would highly appricaite
    Fanx
    Deeps

    ReplyDelete
  42. Thanks - this is what I was looking for - to get started with Android development!

    ReplyDelete
  43. How do you "remember" the login details in an app?

    ReplyDelete
  44. hi ramesh,
    Really this article rocks...i'm using this code in my app..u proved the importance of knowledge sharing..hope u ll keep continuing in posting useful article like this...all the very best..

    ReplyDelete
  45. question.. what should i put in "HttpPost httppost = new HttpPost("http://.......");"?

    Thanks..

    ReplyDelete
  46. thanks for such a useful knowledge sharing

    ReplyDelete
  47. Thanks for this. It is a shame something so simple is so difficult to implement.

    ReplyDelete
  48. I hosted the files here as there seems to be a few requests for them. I hope this is ok with Ramesh.
    http://eggs.wyrdweb.com/androidloginsample.tar.gz

    ReplyDelete
  49. how to increase the height of dialog box , since when i attach some alert msg as textview the button goes down and not visible,so how to increse the height of dialog box in box.xml.....Can anyone help on this issue...

    ReplyDelete
  50. When I run this code, it logs in fine but the subsequent http requests fail because it is not sending the session cookie.
    What am I doing wrong?

    ReplyDelete
  51. [2011-07-18 17:11:53 - CharityAdministrator] Conversion to Dalvik format failed with error 1


    This Error is comming..how to fix it while there is no error in code...plz reply me soon plzz???

    ReplyDelete
  52. Mukesh, to increase the height of the dialog box try to use the android:minWidth=" dp" and
    android:minHeight=" dp" in the layout of your xml file. I have already use it in my project and it works.

    ReplyDelete
  53. guys, need your help badly. I tries running this code and it always fails. A prompt appears saying "Unable to login" with an "OK" button. what might be the problem here. >.< Thanks!

    ReplyDelete
  54. Can you please specify which url I have to use instead of http://....
    HttpPost httppost = new HttpPost("http://...");
    or
    can you give me a server file.

    ReplyDelete
  55. Whats the URL used in httppost

    ReplyDelete
  56. This works great. I replaced xml parsing with Gson, removed the 2 unnecessary classes and it works like a charm.

    ReplyDelete
  57. this is a good example.. how do i create a Log Out button that logs of the user from the application?

    ReplyDelete
  58. Hi,

    A way to logout :
    Remove stored values and come back to main activity.

    Add a button to welcome layout to proceed logout

    And modify welcome class :

    public class Welcome extends Activity{
    Button signout;
    private SharedPreferences mPreferences;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    System.gc();
    setContentView(R.layout.welcome);
    mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
    signout = (Button) findViewById(R.id.btn_logout);
    signout.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    SharedPreferences.Editor editor=mPreferences.edit();
    editor.remove("UserName");
    editor.remove("PassWord");
    editor.commit();
    Intent intent=new Intent(getApplicationContext(),LoginActivity.class);
    startActivity(intent);
    finish();
    }
    });
    }
    }

    ReplyDelete
  59. And for those who wonder how to get login :
    As explained here, your server need to return a xml file, not only a kind of print screen.

    For example in php with username and passowrd are set to 'demo' to succeed a well login.
    Of course, you can change it to perform a data base connection to retrieve some usable user informations.

    header('Content-type: application/xml');
    //here important to return the expected file.
    header('Content-Disposition: attachment; filename="login.xml"');

    if (isset($_POST["username"]) && isset($_POST["password"])) {
    $username = $_POST["username"];
    $password = $_POST["password"];
    ob_start();
    if ( ($username == 'demo') && ($password =='demo') ) {
    echo '< login>< status>SUCCESS< /status>< message>Connexion au serveur< /message>< /login>';
    } else {
    echo '< login>< status>ERROR< /status>< message>Echec de connexion< /message>< /login>';
    }
    ob_end_flush();
    }
    }

    Remove useless space in echo lines for every xml tags.

    Don't forget to change also the line in LoginActivity to connect to your php script :

    HttpPost httppost = new HttpPost("http://www.example.com/login.php");

    ReplyDelete
    Replies
    1. hey osiris, what does demo in this case represent? and dont you need to select anything from the mysql table or post anything? thanx.

      Delete
  60. Hi! Thanks for all, but how can i do this with Servlet? Is it possible?

    ReplyDelete
  61. @studiOOsiris
    I still did not understood what exactly i have to do for login.
    i have to host login.php page on web?
    what should be there in login.php?

    ReplyDelete
  62. i m getting a lot of errors in the code..kindly mail me the correct code

    ReplyDelete
  63. my id is huma.199@hotmail.com..reply soon

    ReplyDelete
  64. i am getting problem in url coz it not accepts the "http://localhost/.." or "http://192.168.1.32:8080/.." plz help what url??
    i am using wamp on my d:\ drive

    ReplyDelete
  65. localhost in emulator is "http://10.0.2.2"

    ReplyDelete
  66. 5. In LoginActivity.java, change line 117 to
    List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();

    6. Comment out line 11 in that file.
    ?????
    i dont knw what to do ... error
    can you please send me a right code on
    arslan_ahmad99@hotmail.com

    ReplyDelete
  67. i get 3 types of errors


    1) id can't be resolved error every time the line (R.id.something) shows up in the code
    2) welcome can't be resolved at setContentView(R.layout.welcome); on Welcome.java
    3) loginerror can't be resolved at setContentView(R.layout.loginerror); in LoginError.java

    Any idea why?

    ReplyDelete
    Replies
    1. put the loginerro.xml & Welcome.xml File in the res layout folder

      Delete
  68. have u tried cleaning up the project ??

    ReplyDelete
  69. This sample project always response "unable to login" message.when am entered correct username and password that time also saying "unable to login" error is displayed...but my logcat having no error...

    ReplyDelete
  70. Please send me code of project with eclipse. Thanks! My emails is tuanlq89pt@gmail.com

    ReplyDelete
  71. anyone send me the right code please ... my email is nourkhcs@gmail.com

    ReplyDelete
  72. Kindly send me the code in eclipse.. i am facing id error, kindly send me code in correct runable form
    thanxxx
    my id is sweaty_321@yahoo.com

    ReplyDelete
  73. Very Nice Tutorial for xml parsing

    ReplyDelete
  74. gandu project bana ke nahi rakh sakta tha ab tera pio ye sab samjhay ga. Alag alag rakha wa hai. Aik sath jor ke nahi rakh sakta tha. Pori file hi dal deta to mot ajata. Hammad Bashir gandu hai.

    ReplyDelete
  75. you can send code for me. I can't do it.Email: toitim_nguoiyeu@yahoo.com. Thank you very much....^^!!

    ReplyDelete
  76. Kindly send me the project code in eclipse.. i am getting errors in this project, kindly send me code in correct runable form...
    my id is vamshi0408@gmail.com

    ReplyDelete
  77. hi ..thank you for the tutorial.
    i was successfully run your code but i got one problem with it that is when i replace the line :
    "HttpPost httppost = new HttpPost("http:.....");"

    with my own url, it shows unable to login. did you know why? i really need a reply for this

    rply plz...

    thank you,

    ReplyDelete
  78. hi frends,
    i m new to android programing, n I found this article very useful. i tried n run this project but it has nt asked for username and password... y? i m surprised.
    pls help
    pls mail solution at vpsonkar@gmail.com

    ReplyDelete
  79. Hi. Im new in Android Programming and I have given a Task that I need to create a class that can connect to a server. for example to this link. How to do it? please email me: newandroidbie@yahoo.com

    ReplyDelete
  80. I have add the code into my project, I am connecting to the host. I want the customer to be able to login. I have an account on the host login, but unable to successfully connect. If anybody can help me to get this working it will be greatly appreciated.
    Code below:
    public class dcMenu extends Activity {
    /** Called when the activity is first created. */
    private static final String TAG = "Login";
    Button signin;
    String loginmessage = null;
    Thread t;
    private SharedPreferences mPreferences;
    ProgressDialog dialog;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
    if (!checkLoginInfo()) {
    signin = (Button) findViewById(R.id.btLogin);
    signin.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    showDialog(0);
    t=new Thread() {
    public void run() {
    tryLogin();
    }
    };
    t.start();
    }
    });
    }
    else {
    /*Directly opens the Welcome page, if the username and password is already available
    in the SharedPreferences*/
    Intent intent=new Intent(getApplicationContext(),Welcome.class);
    startActivity(intent);
    finish();
    }
    }
    @Override
    protected Dialog onCreateDialog(int id) {
    switch (id) {
    case 0: {
    dialog = new ProgressDialog(this);
    dialog.setMessage("Please wait while connecting...");
    dialog.setIndeterminate(true);
    dialog.setCancelable(true);
    return dialog;
    }
    }
    return null;
    }
    private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
    String loginmsg=(String)msg.obj;
    if(loginmsg.equals("SUCCESS")) {
    removeDialog(0);
    Intent intent=new Intent(getApplicationContext(),Welcome.class);
    startActivity(intent);
    finish();
    }
    }
    };

    ReplyDelete
  81. And the rest of the code:
    public void tryLogin() {
    Log.v(TAG, "Trying to Login");
    EditText etxt_user = (EditText) findViewById(R.id.etUsername);
    EditText etxt_pass = (EditText) findViewById(R.id.etPassword);
    String username = etxt_user.getText().toString();
    String password = etxt_pass.getText().toString();
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://208.115.59.195/dealernetwork.com");
    List nameValuePairs = new ArrayList(2);
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));
    try {
    UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nameValuePairs,
    HTTP.UTF_8);
    httppost.setEntity(p_entity);
    HttpResponse response = client.execute(httppost);
    Log.v(TAG, response.getStatusLine().toString());
    HttpEntity responseEntity = response.getEntity();
    Log.v(TAG, "Set response to responseEntity");

    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();
    LoginHandler myLoginHandler = new LoginHandler();
    xr.setContentHandler(myLoginHandler);
    xr.parse(retrieveInputStream(responseEntity));
    ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
    if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) {
    // Store the username and password in SharedPreferences after the successful login
    SharedPreferences.Editor editor=mPreferences.edit();
    editor.putString("UserName", username);
    editor.putString("PassWord", password);
    editor.commit();
    Message myMessage=new Message();
    myMessage.obj="SUCCESS";
    handler.sendMessage(myMessage);
    } else if(parsedLoginDataSet.getExtractedString().equals("ERROR")) {
    Intent intent = new Intent(getApplicationContext(), LoginError.class);
    intent.putExtra("LoginMessage", parsedLoginDataSet.getMessage());
    startActivity(intent);
    removeDialog(0);
    }
    } catch (Exception e)
    {
    Intent intent = new Intent(getApplicationContext(), LoginError.class);
    intent.putExtra("LoginMessage", "Unable to login");
    startActivity(intent);
    removeDialog(0);
    }
    }
    private InputSource retrieveInputStream(HttpEntity httpEntity) {
    InputSource insrc = null;
    try {
    insrc = new InputSource(httpEntity.getContent());
    } catch (Exception e) {
    }
    return insrc;
    }
    //Checking whether the username and password has stored already or not
    private final boolean checkLoginInfo() {
    boolean username_set = mPreferences.contains("UserName");
    boolean password_set = mPreferences.contains("PassWord");
    if ( username_set || password_set ) {
    return true;
    }
    return false;
    }
    }

    ReplyDelete
  82. Guys pls help me on how to connect my App to use a Global server because i m creating a game tha i will like individual users play it through server

    ReplyDelete
  83. sir i want to make a project in the project login and logout with authenication token use for logout using webservices asp.net plz send men code for login and logout

    ReplyDelete
  84. plz send men mail fiazsial@gmail.com

    ReplyDelete
  85. Bonjour !

    Code incomplet !! Merci à studiOOsiris de l'avoir complété !!


    Jerry^

    ReplyDelete
  86. hello, please provide what url should v give to that line HttpPost httppost = new HttpPost("http://.......");

    ReplyDelete
  87. Thank you very much, this is very useful

    ReplyDelete