Pages

Sunday, August 26, 2012

Login application in Android!!

In my previous article I have explained about Button and event for Button. Let's jump in deep in these events.

Here is a program for Login. This application will ask you credential to enter, will provide appropriate message on some wrong attempt and will allow you to go to next screen on successful Lgoin.

In this application we'll need two activities, one is the initial which ask user for credential and second which displays user name on successful login. To add another activity to you Android project follow below steps.

1. Right click on your project and go toNew -> Others...
2. Select Android Activity from Android option.
3. Keep selecting Blank Activity on screen and press next.
4. Give your new Activity's name, here I have given Welcome.

So, after creating new activity two new things will be added in your project.

1. Welcome.java in src folder
2. activity_welcome.xml file in res -> layout folder.

In this application you only need to design activity_login.xml.

1. Design Layout:

I have used some new layout in this application and some new widgets. Take a look at screen and an XML code of activity_login.xml layout of Login application design.


I have taken two EditText and two Buttons. Take a look at below XML code for above design.
Code of activity_login.xml



        

        
        
        
            
      


Here in this design I have taken two <LinearLayout>, the first one with vertical orientation which arrange both EditText plus the second <LinearLayout> in a column. The second <LinearLayout> with horizontal orientation which arrange both Buttons in a Row. 

Second layout and both EditText reside inside first layout and both button reside inside second layout.

Thats it, design finished here, let's move on to resources.

2. Add or Create resources:

 I have created some resources in string.xml file. Below is code for that.



    Login
    Hello world!
    Settings
    Login
    Enter Username
    Enter Password
    Sign In
    Clear
    Welcome





3. Write class file:

In class file we are going to code some validations and events. You have to write below code in you Login.java file.

package com.android.login;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.text.InputType;

public class Login extends Activity {

 EditText username;
 EditText password;
 Button signin;
 Button clear;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        username = (EditText) findViewById(R.id.edit_username);
        password = (EditText) findViewById(R.id.edit_password);
        signin = (Button) findViewById(R.id.btn_signin);
        clear = (Button) findViewById(R.id.btn_clear);
        
        username.setOnTouchListener(new OnTouchListener() {
   
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    int inType = username.getInputType();   //backup input type
    username.setInputType(InputType.TYPE_NULL);  //disable soft input
    username.onTouchEvent(event);     //call native handler
    username.setInputType(inType);     //restore input type
    
    return true;         //consume touch even
   }
  });

        password.setOnTouchListener(new OnTouchListener() {
   
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    int inType = password.getInputType();   //backup input type
    password.setInputType(InputType.TYPE_NULL);  //disable soft input
    password.onTouchEvent(event);     //call native handler
    password.setInputType(inType);     //restore input type
    
    return true;         //consume touch even
   }
  });
        
        clear.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    username.setText("");
    password.setText("");
    username.requestFocus();
   }
  });
        
        signin.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    if(username.getText().toString().equals("") || password.getText().toString().equals(""))
    {
     Toast.makeText(Login.this, "Invalid Username/Password", Toast.LENGTH_LONG).show();
    }
    else if(username.getText().toString().equals("android") && password.getText().toString().equals("rises"))
    {
     Intent i = new Intent(Login.this,Welcome.class);
     i.putExtra("user", username.getText().toString());
     startActivity(i);
    }
    else
    {
     Toast.makeText(Login.this, "Invalid Username/Password", Toast.LENGTH_LONG).show();
    }
   }
  });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }    
}

As you can see in Java file I have taken objects of both EditText and Button in onCreate() method. 

Let's take a look at all methods in details. 

1. username.setOnTouchListener(new OnTouchListener):

If you have seen in any Android phone, when you touch on any text box, a key board on the screen come up. So, in case if your phone have qwerty keyboard in your phone you have to block that virtual key board on screen. I have written code to block that virtual code in this method.

This method will fire when user touch on the username text box and date from text box will copied to an integer variable, then text box will be set to Null by setInputType(int) method.

Same I have coded for password text box.

2. clear.setOnClickListener():

In this method I have cleared both text box and moved focus to username text box.
3. signin.setOnClickListener():

When user click on this button, if credentials are right welcome screen will come up, other wise an error message will flash on screen.

To flash message on screen I have used Toast

Toast.makeText(Login.this, "Invalid Username/Password", Toast.LENGTH_LONG).show();

makeText() of Toast class used to create flash message. First argument is this pointer of the screen class where you want to flash message. Second argument is the message you want to flash and third is time duration. Time duration can only set either LENGTH_LONG or LENGTH_SHORT. 

show() method actually display message on screen.

This all process executes if user enter wrong credential but, if user enter correct credential new activity will execute. So, you have to learn how to call new activity.

In this application another activity created is Welcome. On successful login the else if part will execute. I have create object of Intent class. Intent is a class which you can use to call another activity. Calling activity can be user created or system created like Contacts, Message, etc.

Intent i = new Intent(Login.this, Welcome.class);

Above statement will create i object of Intent class. Object is created by calling  constructor. First argument in constructor is this pointer of activity from where you are starting new activity. Second argument is class of the calling activity.

i.putExtra("user", username.getText());

Above method is used to pass some data to next activity. This will pass username who is signing in to the application. "user" is key to access the username in activity we are calling.

startActivity(i);

This method belong to Activity class. You can use this method to call new activity. As an argument you just need to pass Intent class' object.
This all is enough to start new activity. Let's check out what happening in this new activity. 

Below is a code of Welcome.java file.

package com.android.login;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class Welcome extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        TextView tv = (TextView)findViewById(R.id.textWelcome);
        Bundle b = getIntent().getExtras();
        String user = b.getString("user");
        tv.setText("Welcome, " + user + "!");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_welcome, menu);
        return true;
    }

    
}

In this activity I have just display username in a textview which passed from Login activity. You know how to create object of textview using findViewById.
Here I have use Bundle class, take a look at it.

Bundle b = getIntent().getExtras();

getIntent() is method of activity class. It returns intent that started this activity. In this case Login activity started Welcome activity so, getIntent() here will return intent of Login activity.

getExtras() is method of Intent class. It receives all extended data from intent. Here it will return Bundle object.

String user = b.getString("user");

This will return the value associated with the given key. Here in this application key is "user" and value is username. So, string user will get the username passed from Login activity.

The complete application will look something like this.

Login Activity
  
Welcome Activity


Thats it. You are done!!!

No comments:

Post a Comment