How to switch between Activities

In Android user interface is displayed through an activity. In Android app development you might face situations where you need to switch between one Activity (Screen/View) to another. In this tutorial I will be discussing about switching between one Activity to another and sending data between activities.

Before getting into complete tutorial I am giving the code snippets for handling activities. Lets assume that our new Activity class name is SecondScreen.java

Opening new Activity

To open new activity following startActivity() or startActivityForResult() method will be used.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);

 

Sending parameters to new Activity

To send parameter to newly created activity putExtra() methos will be used.

i.putExtra("key", "value");
// Example of sending email to next screen as
// Key = 'email'
// value = 'myemail@gmail.com'
i.putExtra("email", "myemail@gmail.com");

 

Receiving parameters on new Activity

To receive parameters on newly created activity getStringExtra() method will be used.

Intent i = getIntent();
i.getStringExtra("key");
// Example of receiving parameter having key value as 'email'
// and storing the value in a variable named myemail
String myemail = i.getStringExtra("email");

 

Opening new Activity and expecting result

In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result
// Function to read the result from newly created activity
@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
             // Storing result in a variable called myvar
             // get("website") 'website' is the key value result data
             String mywebsite = data.getExtras().get("result");
        }
    }

 

Sending result back to old activity when StartActivityForResult() is used

Intent i = new Intent();
// Sending param key as 'website' and value as 'androidhive.info'
i.putExtra("website", "AndroidHive.info");
// Setting resultCode to 100 to identify on old activity
setResult(100,in);

 

Closing Activity

To close activity call finish() method

finish();

 

Add entry in AndroidManifest.xml

To run our application you should enter your new activity in AndroidManifest.xml file. Add new activity between <application> tags

<activity android:name=".NewActivityClassName"></activity>

 

Let’s Start with a simple project

So now we have all the code snippets related to activities. In this tutorial i created two xml layouts(screen1.xml, screen2.xml) and two Acvities(FirstScreenActivity.java, SecondScreenActivity.java). The following diagram will give you an idea about the file structure you will be need in this tutorial.

Directory Structure

Now lets start by creating a simple project.

1. Create a new project File -> Android Project. While creating a new project give activity name as FirstScreenActivity.
2. Now you need to create user interface for the FirstScreenActivity.java
3. Create a new xml file in layout folder or rename the main.xml to screen1.xml
Right Click on Layout -> New -> Android XML file and name it as screen1.xml
4. Now insert the following code in screen1.xml to design a small layout. This layout contains simple form with a button.

<?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:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Name: "/>
    <EditText android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Email: "
        />
    <EditText android:id="@+id/email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>
    <Button android:id="@+id/btnNextScreen"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Send to Next Screen"
            android:layout_marginTop="15dip"/>
</LinearLayout>
Screen1.xml output

5. Now open your FirstScreenActivity.java and Type the following code. In the following code we are creating a new Intent and passing parameters on clicking button.

package com.example.androidswitchviews;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class FirstScreenActivity extends Activity {
    // Initializing variables
    EditText inputName;
    EditText inputEmail;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen1);
        inputName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
        //Listening to button event
        btnNextScreen.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                //Starting a new Intent
                Intent nextScreen = new Intent(getApplicationContext(), SecondScreenActivity.class);
                //Sending data to another Activity
                nextScreen.putExtra("name", inputName.getText().toString());
                nextScreen.putExtra("email", inputEmail.getText().toString());
                Log.e("n", inputName.getText()+"."+ inputEmail.getText());
                startActivity(nextScreen);
            }
        });
    }
}

6. Create a class called SecondScreenActivity.java. Right Click on src/yourpackagefolder -> New -> Class and name it as SecondScreenActivity.java

Android creating new class

7. Now we need interface for our Second Actvity. Create a new xml file and name it as screen2.xml.
Right Click on Layout -> New -> Android XML file and name it as screen2.xml. Insert the following code in screen2.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="You Entered..."
            android:textSize="25dip"
            android:gravity="center"
            android:layout_margin="15dip"/>
  <TextView android:id="@+id/txtName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dip"
            android:textSize="18dip"/>
  <TextView android:id="@+id/txtEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dip"
            android:textSize="18dip"/>
  <Button android:id="@+id/btnClose"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dip"
            android:text="Close"/>
</LinearLayout>

8. Now open SecondScreenActivity.java and type the following code. Here we are simply reading the parameters and displaying them on to screen

package com.example.androidswitchviews;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SecondScreenActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);
        TextView txtName = (TextView) findViewById(R.id.txtName);
        TextView txtEmail = (TextView) findViewById(R.id.txtEmail);
        Button btnClose = (Button) findViewById(R.id.btnClose);
        Intent i = getIntent();
        // Receiving the Data
        String name = i.getStringExtra("name");
        String email = i.getStringExtra("email");
        Log.e("Second Screen", name + "." + email);
        // Displaying Received data
        txtName.setText(name);
        txtEmail.setText(email);
        // Binding Click event to Button
        btnClose.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                //Closing SecondScreen Activity
                finish();
            }
        });
    }
}

9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below

<?xml version="1.0" encoding="utf-8"?>
      package="com.example.androidswitchviews"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-sdk android:minSdkVersion="8" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FirstScreenActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- Add new Activity class name here --->
        <activity android:name=".SecondScreenActivity"></activity>
    </application>
</manifest>

10. Finally run your project by right clicking on your project folder -> Run As -> 1 Android Application. You can see the application is running by switching between screens. The below image is output screenshots of both xml files.

Switching between views in Android Output

External Fonts

Loading external fonts in your android application is very easy. It can be achieved with only two lines of code.

Start a new Project

1. Create a new project and fill the required details. File ⇒ New Project.
2. Create a folder called fonts under assets folder and place all your fonts in it. (Folder name can be anything)

android using external fonts

3. Open your main.xml and create a simple textview.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#222222" >
    <TextView
        android:id="@+id/ghost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textSize="70dip"
        android:gravity="center"
        android:textColor="#ef0000"
        android:layout_marginTop="50dip"
        android:text="ghost" />
</LinearLayout>

4. Now open your MainActivity class file and try following code. In the following code i am importing font from assets folder and using TypeFace class i am applying custom font on textview label.

AndroidExternalFontsActivity.java
package com.example.androidhive;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class AndroidExternalFontsActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Font path
        String fontPath = "fonts/Face Your Fears.ttf";
        // text view label
        TextView txtGhost = (TextView) findViewById(R.id.ghost);
        // Loading Font Face
        Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
        // Applying font
        txtGhost.setTypeface(tf);
    }
}

5. Run your project.

android loading external fonts

How to make Zip File in sdcard

Make a Compress Class.
In this class you pass the arguement which files you want to zip.
============================================================================================

import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Compress {
private static final int BUFFER = 2048;

private String[] _files;
private String _zipFile;

public Compress(String[] files, String zipFile) {
_files = files;
_zipFile = zipFile;
}

public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(new File(_zipFile));

ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));

byte data[] = new byte[BUFFER];

for (int i = 0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i]
.lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}

out.close();
} catch (Exception e) {
e.printStackTrace();
}

}

}

================================================================================================
i will compress 2 pdf file… see the code below

String zipName = "/zipname.zip";

// Folder Name you want to create
String newFolder = "/ali";

String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();

File myNewFolder = new File(extStorageDirectory + newFolder);
if (myNewFolder.exists()) {

} else {
myNewFolder.mkdir();
}
String[] files = new String[] {
extStorageDirectory + "/Bs.pdf",
extStorageDirectory + "/Bs2.pdf" };

newFolder = extStorageDirectory + newFolder;

Compress c = new Compress(files, newFolder + "" + zipName);
c.zip()

================================================================================================

If that all makes sense to you already, then you probably won't be interested in my explanations below, otherwise, keep reading. 🙂

private static final int BUFFER = 2048;

private String[] _files;
private String _zipFile;

These are the properties that I've declared for the class.

The first is the BUFFER (for reading the data and writing it to the zip stream), second is the _files array, which will hold all the files (path as well) that will be zipped up, and the third is the name of the zip file (path as well).

public Compress(String[] files, String zipFile) {
_files = files;
_zipFile = zipFile;
}

This is the constructor, which is the first thing that gets called when instantiating the class – you'll pass it an array of the files you wish to zip, and a string of what the name of the final zip file will be. It then saves this data in the properties, to be used when you call the zip method.

BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(_zipFile);

ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

byte data[] = new byte[BUFFER];

Next we move into the zip method – the first things we do is setup our BufferedInputStream, which we'll be using to read the data from the file input stream (each file in the files array).

The FileOutputStream creates the zip file, and sets up the stream, which we then pass to the ZipOutputStream for writing to.

If you want more in depth details about each of these objects (classes), then do a quick search for FileOutputStream or ZipOutputStream in Google.

for(int i=0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);

FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);

ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);

int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}

origin.close();
}

out.close();

And here we have the main loop, which will go through each file in the _files array and compress each one into the zip file.

Here we first setup a FileInputStream for reading the files – the BufferedInputStream will manage the amount of data that it'll be reading at a time (based on the BUFFER).

The ZipEntry is used for adding the actual file/directory structure – for example, if you add '/mnt/sdcard/data/myzip.zip', it would actually create that directory structure in the zip file, so if you want to just add the file into the root of the zip, you'll need to parse it out. Personally, I just used substring, and lastIndexOf to grab the file at the end.

Once the entry is set, you can add it to the zip output stream using out.putNextEntry.

Now we have another loop, which will be used for reading the data, 2048 bytes at a time, and write it to the zip output stream (to the new entry location).

Finally, we clean up – close the streams.

I hope that made sense, and if I can change anything to make it more understandable, please let me know.

Hide Scrollbar In WebView

mWebView = (WebView) findViewById(R.id.webview);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

Get to know the orientation of your activity

 int i = getResources().getConfiguration().orientation;

  if (i == Configuration.ORIENTATION_PORTRAIT) {
  
    } else {
  
    }

i == 0 means Orientation is landscape 

webview previous page using back button

Extra features

You may have noticed that the widget doesn’t have a toolbar. This is intended, as you would normally launch the native web browser app if you want navigation capabilities. There is, however, a way to control it rogrammatically. Try invoking one of the following methods on the instance of your widget:

  • reload(): Refreshes and re-renders the page.
  • goForward(): Goes one step forward in browser history.
  • goBack(): Goes one step back in browser history.
  • cangoForward() Return true if webview has a forward history
  • cangoBack() Return true if webview has a back history

@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}

}
return super.onKeyDown(keyCode, event);
}

onBackPressed() event will not work here

///////////////////////////////////////////////////////////////

WebView Basic

There is 8 Parts of webview basics

The WebView enables you to embed a web browser in your activity. This is very useful if your application needs to embed some web content, such as maps from some other providers, and so on. The following Try It Out shows how you can programmatically load the content of a web page and dis-
play it in your activity


1. Launching a web view with an Intent

There are a couple of different ways to utilize a “web view” in an Android application. The easiest way, as usual is by using an Intent. This example uses an Intent to launch the browser application:

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class WebIntent extends Activity
{
Button theButton;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
theButton = (Button) findViewById(R.id.Button01);
theButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse(“http://www.mobvcasting.com/mmtest/index.html&#8221;);
intent.setData(uri);
startActivity(intent);
}
});

}
}

What follows is the HTML source of the index.html page referenced above:
<html>
<head>
<title>Hello World</title>
<script type=”text/javascript”>
alert(“JavaScript Alert”);
document.writeln(“Line Generated By JavaScript”);
</script>
</head>
<body>
<h1>Hello There</h1>
<a href=”#” onClick=”window.jsinterface.specialClick();”>Click Me</a>
</body>
</html>

Running the above code with this HTML, you’ll notice a couple of things. First when the page loads an Alert pops up that  says “JavaScript Alert”. In the body of the document you’ll see first a line of text that says “Line Generated By JavaScript” and then a link that says “Click Me”.

The two JavaScript references show that JavaScript is running and fully implemented in the browser view. When you click on the “Click Me” link though, nothing will probably happen. This is not a bug, it just points the way to something we’ll be doing later on.

———————————————————————————

2.Displaying a web page inside an Activity using WebView

Using the WebView object we can create our own browser view.
It requires that we added the following permission request to our

AndroidManifest.xml file:
<uses-permission android:name=”android.permission.INTERNET”/>

Here is an example Activity using a WebView object:
package com.mobvcasting.webviewexample;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebviewExample extends Activity
{
WebView webview;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
webview.loadUrl(“http://www.yahoo.com&#8221;);

}

}

To use the WebView to load a web page, you use the loadUrl() method, like this

webview.loadUrl(“http://www.yahoo.com&#8221;);

You’ll notice that this behaves a bit differently loading the same HTML as the previous example. This one does not show the JavaScript Alert and may or may not show the “Line Generated By JavaScript”. I will tell you later in this section.

———————————————————————————

3. Load Image and setBuiltInZoomControls

main.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >

<WebView
android:id=”@+id/webview1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />

</LinearLayout>

MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

WebView wv = (WebView)findViewById(R.id.webview1);

WebSettings webSettings = wv.getSettings();

webSettings.setBuiltInZoomControls(true);


wv.loadUrl(“http://ecx.images-amazon.com/images/I/41HGB-W2Z8L._SL500_AA300_.jpg&#8221;);

}

To display the built-in zoom controls, you need to first get the WebSettings property from the WebView and then call its setBuiltInZoomControls() method

WebSettings webSettings = wv.getSettings();

webSettings.setBuiltInZoomControls(true);

shows the built-in zoom controls that appear when you use the mouse to click and drag the content of the WebView on the Android Emulator

below 3rd one pic has been attached mistakely *

———————————————————————————

4. URL REDIRECTS to ANOTHER URL

Sometimes when you load a page that redirects you (such as load-
ing http://www.wrox.com redirects you to http://www.wrox.com/wileyCDA), WebView
will cause your application to launch the device’s browser applica-
tion to load the desired page. For example, if you ask the WebView
to load http://www.wrox.com, Wrox.com will automatically redirect you to
http://www.wrox.com/WileyCDA/. In this case, your application will auto-
matically launch the device’s browser application to load your page.

To prevent this from happening, you need to implement the WebViewClient class and override the shouldOverrideUrlLoading() method, as shown in the following example

@Override
public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);

setContentView(R.layout.main);


WebView wv = (WebView)findViewById(R.id.webview1);
wv.setWebViewClient(new Callback());
WebSettings webSettings = wv.getSettings();
webSettings.setBuiltInZoomControls(true);
wv.loadUrl(“http://www.wrox.com&#8221;);

}

private class Callback extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return(false); // will not override
}
}

———————————————————————————

5.  HTML string and load it into the WebView

using the loadDataWithBaseURL()

WebView wv = (WebView)findViewById(R.id.webview1);
WebSettings webSettings = wv.getSettings();
webSettings.setBuiltInZoomControls(true);

final String mimeType = “text/html”;
final String encoding = “UTF-8”;
String html = “<H1>A simple HTML page</H1><body>” +
“<p>The quick brown fox jumps over the lazy dog</p>”;
wv.loadDataWithBaseURL(“”, html, mimeType, encoding, “”);

———————————————————————————

6. Load HTML File from assets folder

WebView wv = (WebView) findViewById(R.id.webview1);
wv.loadUrl(“file:///android_asset/index.html”);

———————————————————————————

7. Read PDF online in WebView

WebView webview = (WebView) findViewById(R.id.webview1); 

String pdf = “http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf&#8221;;
webview.loadUrl(“http://docs.google.com/gview?embedded=true&url=&#8221; + pdf);

————————————————————————————————-

8. display image and put files in asset folder

To display that image as part of the web page, I can use it’s relative path:
<img src=”images/happydog.jpg” width=”320″ />
or it’s absolute path:
<img src=”file:///android_asset/images/happydog.jpg” width=”320″ />

Linking Activities Using intent For Beginners Part 1

An Android application can contain zero or more activities. When your application has more than one activity, you may need to navigate from one activity to another. In Android, you navigate between activities through what is known as an intent.
The best way to understand this very important but somewhat abstract concept in Android is to experience it fi rsthand and see what it helps you to achieve.

Manifest.xml

<?xml​version=”1.0”​encoding=”utf-8”?>
<manifest​xmlns:android=”http://schemas.android.com/apk/res/android”
​​​​​​package=”net.learn2develop.Activities”
​​​​​​android:versionCode=”1”
​​​​​​android:versionName=”1.0”>
​​​​<application​android:icon=”@drawable/icon”​android:label=”@string/app_name”>

​​​​​​​​<activity​android:name=”.MainActivity” ​​​​​​​​​​​​​​​​​​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=”.Activity2”
​​​​​​​​​​​​​​​​ android:label=”Activity 2”>
​​​​​​​​​​​​<intent-filter>
​​​​​​​​​​​​​​​​<action android:name=”com.example.ACTIVITY2” />
​​​​​​​​​​​​​​​​<category android:name=”android.intent.category.DEFAULT” />
​​​​​​​​​​​​</intent-filter>
​​​​​​​​</activity>
​​​​</application>

 

activity2.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:layout_width=”fill_parent”​
​​​​android:layout_height=”wrap_content”
​​​​android:text=”This is Activity 2!”
​​​​/>
</LinearLayout>

============================================

Activity2.java file,

import android.app.Activity;
import android.os.Bundle;
public class Activity2 extends Activity {
​​​​@Override
​​​​public void onCreate(Bundle savedInstanceState) {
​​​​​​​​super.onCreate(savedInstanceState);
​​​​​​​​setContentView(R.layout.activity2);
​​​​}
}

 

===========================================

make main.xml file and drag button with the name of button1

MainActivity.java

 
public​ class ​MainActivity​ extends ​Activity​{

​​​​@Override
​​​​public ​void ​on Create(Bundle​savedInstanceState)​{
​​​​​​​​super.onCreate(savedInstanceState);

​​​​​​​​setContentView(R.layout.main);

Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

startActivity(new Intent(“com.example.ACTIVITY2”));

}
});

​​​​}

}

 

Explanation

Here, you have added a new activity to the application. Note the following:
The name of the new activity added is “ ➤➤ Activity2”.
The label for the activity is named “ ➤➤ Activity​2”.
The intent filter name for the activity is “ ➤➤ com.example.ACTIVITY2”. Other activities that wish to call this activity will invoke it via this name. Ideally, you should use the reverse domain name of your company as the intent filter name in order to reduce the chances of another application having
the same intent filter. The next section discusses what happens when two or more activities have the  same intent filter.
The category for the intent filter is “ ➤➤ android.intent.category.DEFAULT”. You need to add this to the intent filter so that this activity can be started by another activity using the startActivity() method (more on this shortly).

 

​startActivity(new Intent(“com.example.ACTIVITY2”));

Activities in Android can be invoked by any application running on the device. For example, you can create a new Android project and then display Activity2 by using its net.learn2develop.ACTIVITY2 intent filter. This is one of the fundamental concepts in Android that enables an application to invoke
another easily.
If the activity that you want to invoke is defined within the same project, you can rewrite the preceding statement like this:
​​​​​​​​​​​​startActivity(new​Intent(this,​Activity2.class));
However, this approach is applicable only when the activity you want to  display is within the same project as the current activity

setMultiChoiceItems

main.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” >

<Button
android:id=”@+id/btn_dialog”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Click to display a dialog” />
</LinearLayout>

======================================================

MainActivity.java

 

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
CharSequence[] items = { “Google”, “Apple”, “Microsoft” };
boolean[] itemsChecked = new boolean [items.length];

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(0);

}
});

}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(“This is a dialog with some simple text…”)
.setPositiveButton(“OK”, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
Toast.makeText(getBaseContext(),
“OK clicked!”, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(“Cancel”, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
Toast.makeText(getBaseContext(),
“Cancel clicked!”, Toast.LENGTH_SHORT).show();
}
})
.setMultiChoiceItems(items, itemsChecked, new
DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(),
items[which] + (isChecked ? ” checked!”: ” unchecked!”),
Toast.LENGTH_SHORT).show();
}
}
)
.create();

}
return null;
}
}

 

 

 

================================================

Explanation:

​Button​btn​=​(Button)​findViewById(R.id.btn_dialog);
​​​​​​​​btn.setOnClickListener(new​View.OnClickListener()​{
​​​​​​​​​​​​public​void​onClick(View​v)​{
​​​​​​​​​​​​​​​​showDialog(0);
​​​​​​​​​​​​}
​​​​​​​​});
The onCreateDialog() method is a callback for creating dialogs that are managed by the activity. When you call the showDialog() method, this callback will be invoked. The showDialog() method accepts an integer argument identifying a particular dialog to display.
To create a dialog, you use the AlertDialog class’s Builder constructor. You set the various properties,  such as icon, title, and buttons, as well as checkboxes:

​​​​@Override
​​​​protected​Dialog​onCreateDialog(int​id)​{
​​​​​​​​switch​(id)​{
​​​​​​​​case​0:
​​​​​​​​​​​​return​new​AlertDialog.Builder(this)
​​​​​​​​​​​​.setIcon(R.drawable.icon)
​​​​​​​​​​​​.setTitle(“This​is​a​dialog​with​some​simple​text…”)
​​​​​​​​​​​​.setPositiveButton(“OK”,​new
​​​​​​​​​​​​​​​​DialogInterface.OnClickListener()​{
​​​​​​​​​​​​​​​​public​void​onClick(DialogInterface​dialog,​
​​​​​​​​​​​​​​​​int​whichButton)
​​​​​​​​​​​​​​​​{
​​​​​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(),
​​​​​​​​​​​​​​​​​​​​​​​​​“OK​clicked!”,​Toast.LENGTH_SHORT).show();
​​​​​​​​​​​​​​​​}
​​​​​​​​​​​​})
​​​​​​​​​​​​.setNegativeButton(“Cancel”,​new
​​​​​​​​​​​​​​​​DialogInterface.OnClickListener()​{
​​​​​​​​​​​​​​​​public​void​onClick(DialogInterface​dialog,
​​​​​​​​​​​​​​​​​​​​int​whichButton)
​​​​​​​​​​​​​​​​{
​​​​​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(),
​​​​​​​​​​​​​​​​​​​​​​​​​​​​“Cancel​clicked!”,​Toast.LENGTH_SHORT).show();
​​​​​​​​​​​​​​​​}
​​​​​​​​​​​​})
​​​​​​​​​​​​.setMultiChoiceItems(items,​itemsChecked,​new
​​​​​​​​​​​​​​​​DialogInterface.OnMultiChoiceClickListener()​{
​​​​​​​​​​​​​​​​​​​​@Override
​​​​​​​​​​​​​​​​​​​​public​void​onClick(DialogInterface​dialog,​int​which,
​​​​​​​​​​​​​​​​​​​​boolean​isChecked)​{
​​​​​​​​​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(),
​​​​​​​​​​​​​​​​​​​​​​​​​​​​items[which]​+​(isChecked​?​“​checked!”:
​​​​​​​​​​​​​​​​​​​​​​​​​​​​“​unchecked!”),
​​​​​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show();
​​​​​​​​​​​​​​​​​​​​}
​​​​​​​​​​​​​​​​}
​​​​​​​​​​​​)
​​​​​​​​​​​​.create();
​​​​​​​​}
​​​​​​​​return​null;
​​​​}

 

 

The preceding code sets two buttons: OK and Cancel, using
the setPositiveButton() and setNegativeButton() methods,
respectively. You also set a list of checkboxes for users to choose via
the setMultiChoiceItems() method. For the setMultiChoiceItems()
method, you passed in two arrays: one for the list of items to display
and another to contain the value of each item to indicate if they are
checked. When each item is checked, you use the Toast class to
display a message

 

Pick a file using Intent.ACTION_GET_CONTENT

If you have to pick a file in your app, but you don’t want to implement your own file explorer; you can start a activity with intent of Intent.ACTION_GET_CONTENT. Android OS will choice a suitable app with such function for you.

You can get the FILENAME , FOLDER , FULL PATH,EXTENSION

To get extension, we can use the following java code:

int dotposition= file.lastIndexOf(“.”);
filename_Without_Ext = file.substring(0,dotposition);
ext = file.substring(dotposition + 1, file.length());

a new class filename is implemented to get file extention and filename without extention.

If no File Manager installed in your mobile it will show TOAST

Pick a file using Intent.ACTION_GET_CONTENT

 get file extension using java code 

package com.exercise.AndroidPick_a_File; 
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    TextView textFile, textFileName, textFolder;
    TextView textFileName_WithoutExt, textFileName_Ext;

    private static final int PICKFILE_RESULT_CODE = 1;

      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
        
          Button buttonPick = (Button)findViewById(R.id.buttonpick);
          textFile = (TextView)findViewById(R.id.textfile);
          textFolder = (TextView)findViewById(R.id.textfolder);
          textFileName = (TextView)findViewById(R.id.textfilename);
        
          textFileName_WithoutExt = (TextView)findViewById(R.id.textfilename_withoutext);
          textFileName_Ext = (TextView)findViewById(R.id.textfilename_ext);
           
           buttonPick.setOnClickListener(new Button.OnClickListener(){

       @Override
       public void onClick(View arg0) {
        // TODO Auto-generated method stub
               try{
               Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("file/");
            startActivityForResult(intent,PICKFILE_RESULT_CODE);
               }
               catch(ActivityNotFoundException exp){
                Toast.makeText(getBaseContext(), "No File (Manager / Explorer)etc Found In Your Device",5000).show();
               }
               
        
       }}); 
       }
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       // TODO Auto-generated method stub
       switch(requestCode){
       case PICKFILE_RESULT_CODE:
        if(resultCode==RESULT_OK){
        
         String FilePath = data.getData().getPath();
         String FileName = data.getData().getLastPathSegment();
         int lastPos = FilePath.length() - FileName.length();
         String Folder = FilePath.substring(0, lastPos);
        
         textFile.setText("Full Path: \n" + FilePath + "\n");
         textFolder.setText("Folder: \n" + Folder + "\n");
         textFileName.setText("File Name: \n" + FileName + "\n");
        
         filename thisFile = new filename(FileName);
         textFileName_WithoutExt.setText("Filename without Ext: " + thisFile.getFilename_Without_Ext());
               textFileName_Ext.setText("Ext: " + thisFile.getExt());
        
        }
        break;
       
       }
      }

      private class filename{

       String filename_Without_Ext = "";
       String ext = "";

       filename(String file){
           int dotposition= file.lastIndexOf(".");
           filename_Without_Ext = file.substring(0,dotposition);
           ext = file.substring(dotposition + 1, file.length());
       }

       String getFilename_Without_Ext(){
        return filename_Without_Ext;
       }

       String getExt(){
        return ext;
       }
      }

      }

main.xml

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

    <Button
        android:id="@+id/buttonpick"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="- PICK a file -" />

    <TextView
        android:id="@+id/textfile"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textfolder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textfilename"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textfilename_withoutext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textfilename_ext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>