Login and connect with server using Http connection

Posted: 29/03/2013 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&#8221;
      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&#8221; >

      < 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”&gt;
      < 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&#8221; >
      < 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&#8221;
      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://…&#8230;.”);
            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);
      }
}

Advertisements

Trả lời

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Đăng xuất / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Đăng xuất / Thay đổi )

Connecting to %s