You are on page 1of 11

Chap-3.

Starting with Application Coding

Android Intent

Android Intent is the message that is passed between components such as activities, content providers,
broadcast receivers, services etc.

It is generally used with startActivity() method to invoke activity, broadcast receivers etc.

The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do
action. The LabeledIntent is the subclass of android.content.Intent class.

Types of Android Intents


There are two types of intents in android: implicit and explicit.

1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides information
of available components provided by the system that is to be invoked.

For example, you may write the following code to view the webpage.

Intent intent=new Intent(Intent.ACTION_VIEW);  
intent.setData(Uri.parse("http://www.javatpoint.com"));  
startActivity(intent);  

2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class to
be invoked.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);  
startActivity(i);  

Android Implicit Intent Example : -


File: MainActivity.java

package example.javatpoint.com.implicitintent;  
  
import android.content.Intent;  
import android.net.Uri;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
import android.widget.EditText;  
  
public class MainActivity extends AppCompatActivity {  
  
    Button button;  
    EditText editText;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);    
        button = findViewById(R.id.button);  
        editText =  findViewById(R.id.editText);
  
        button.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                String url=editText.getText().toString();  
                Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));  
                startActivity(intent);  
            }  
        });  
    }  
}  
Android Explicit Intent Example: -
ActivityOne class
File: MainActivityOne.java

package example.javatpoint.com.explicitintent;  
  
import android.content.Intent;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.view.View;  
  
public class FirstActivity extends AppCompatActivity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_first);  
    }  
    public void callSecondActivity(View view){  
        Intent i = new Intent(getApplicationContext(), SecondActivity.class);  
        i.putExtra("Value1", "Android By Javatpoint");          i.putExtra("Value2", "Simple Tuto
rial"); 
        // Set the request code to any code you like, you can identify the  
        // callback via this code  
        startActivity(i);  
    } 
}  

ActivityTwo class
File: MainActivityTwo.java

package example.javatpoint.com.explicitintent;  
  
import android.content.Intent;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Toast;  
  
public class SecondActivity extends AppCompatActivity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_second);  
        Bundle extras = getIntent().getExtras();  
        String value1 = extras.getString("Value1");  
        String value2 = extras.getString("Value2");  
        Toast.makeText(getApplicationContext(),"Values are:\n First value: "+value1+  
                "\n Second Value: "+value2, Toast.LENGTH_LONG).show();  
    }  
    public void callFirstActivity(View view){  
        Intent i = new Intent(getApplicationContext(), FirstActivity.class);  
        startActivity(i);  
    } 
}  

Introducing Adapters : -

An adapter acts like a bridge between a data source and the user interface. It reads data from various
data sources, coverts it into View objects and provide it to the linked Adapter view to create UI
components.The data source or dataset can be an Array object, a List object etc.
You can create your own Adapter class by extending the BaseAdapter class, which is the parent class for
all other adapter class. Android SDK also provides some ready-to-use adapter classes, such
as ArrayAdapter, SimpleAdapter etc.
Adapter View
An Adapter View can be used to display large sets of data efficiently in form of List or Grid etc, provided
to it by an Adapter. An Adapter View is capable of displaying millions of items on the User Interface,
while keeping the memory and CPU usage very low and without any noticeable lag. Different Adapters
follow different strategies for this, but the default Adapter provided in Android SDK.

Using Internet Resources: -


With Internet connectivity and WebKit browser, you might well ask if there’s any reason to create native
Internet-based applications when you could make a web-based version instead.

Before you perform any network operations, you must first check that are you connected to that
network or internet e.t.c. For this android provides ConnectivityManager class. You need to instantiate
an object of this class by calling getSystemService() method.

Example: -

String link = "http://www.google.com";

URL url = new URL(link);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.connect();

InputStream is = conn.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

String webPage = "",data="";

while ((data = reader.readLine()) != null){

webPage += data + "\n";

}
Introducing Dialogs: - Sometimes in your application, if you wanted to ask the user
about taking a decision between yes or no in response of any particular action taken by the user, by
remaining in the same activity and without changing the screen, you can use Alert Dialog.

In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class
of AlertDialog.

Syntax: - AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

Refer the example of alert dialog which is given.


In android, you can create following types of Dialogs:

 Alert Dialog

 DatePicker Dialog

 TimePicker Dialog

 Custom Dialog

 Alert Dialog: -This Dialog is used to show a title, buttons (maximum 3 buttons allowed), a
list of selectable items, or a custom layout.

 DatePicker Dialog : - This dialog provides us with a pre-defined UI that allows the user to
select a date.
 TimePicker Dialog : - This dialog provides us with a pre-defined UI that allows the user
to select suitable time.

 Custom Dialog : - You can create your own custom dialog with custom characteristics.

Capturing Date and Time: -


Android provides controls for the user to pick a time or pick a date as ready-to-use dialogs. Each picker
provides controls for selecting each part of the time (hour, minute, AM/PM) or date (month, day, year).
Using these pickers helps ensure that your users can pick a time or date that is valid, formatted
correctly, and adjusted to the user's locale.
public class XYZ extends Activity {

/** Called when the activity is first created. */


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

Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


String formattedDate = df.format(c.getTime());
// formattedDate have current date/time
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();

// Now we display formattedDate value in TextView


TextView txtView = new TextView(this);
txtView.setText("Current Date and Time : "+formattedDate);
txtView.setGravity(Gravity.CENTER);
txtView.setTextSize(20);
setContentView(txtView);
}

Validating and Handling Input data: -


A login application is the screen asking your credentials to login to some particular application. You
might have seen it when logging into facebook,twitter e.t.c

Example for Login screen:

package com.example.sairamkrishna.myapplication;

import android.app.Activity;

import android.graphics.Color;

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 MainActivity extends Activity {

Button b1,b2;

EditText ed1,ed2;

TextView tx1;

int counter = 3;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

b1 = (Button)findViewById(R.id.button);

ed1 = (EditText)findViewById(R.id.editText);

ed2 = (EditText)findViewById(R.id.editText2);

b2 = (Button)findViewById(R.id.button2);

tx1 = (TextView)findViewById(R.id.textView3);

tx1.setVisibility(View.GONE);

b1.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if(ed1.getText().toString().equals("admin") &&

ed2.getText().toString().equals("admin")) {

Toast.makeText(getApplicationContext(),

"Redirecting...",Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(getApplicationContext(), "Wrong

Credentials",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);

tx1.setBackgroundColor(Color.RED);

counter--;

tx1.setText(Integer.toString(counter));

if (counter == 0) {

b1.setEnabled(false);

});

b2.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

finish();

});

You might also like