Android Share Intent Example for URL, Text or Image

Today I’m going to give you an android share intent example that you can use to enable your app to share contents such as URL or text and Image to other apps installed in your Android device like Facebook, Twitter, Messaging, Instagram, Evernote, etc.. Example uses of this code include:

You are building an app that browses a certain website or URL.

Your app generates an image that a user can share.

android share intent example

DOWNLOAD CODE

Android Share Intent Example Step by Step

Step 1: Prepare XML Layout, we’ll have activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/buttonShareTextUrl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Share Text or URL" />

    <Button
        android:id="@+id/buttonShareImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/buttonShareTextUrl"
        android:text="Share Image" />

</RelativeLayout>

Step 2: Inside the onCreate method of MainActivity.java, put the buttons and OnClickListener handlers.

// listeners of our two buttons
View.OnClickListener handler = new View.OnClickListener() {
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.buttonShareTextUrl:
			shareTextUrl();
			break;

		case R.id.buttonShareImage:
			shareImage();
			break;
		}
	}
};

// our buttons
findViewById(R.id.buttonShareTextUrl).setOnClickListener(handler);
findViewById(R.id.buttonShareImage).setOnClickListener(handler);

Step 3: As you’ve noticed, we have shareTextUrl() method that will be triggered every time the user clicks on the “Share Text or URL” button.

private void shareTextUrl() {
	Intent share = new Intent(android.content.Intent.ACTION_SEND);
	share.setType("text/plain");
	share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

	// Add data to the intent, the receiving app will decide
	// what to do with it.
	share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");
	share.putExtra(Intent.EXTRA_TEXT, "http://www.codeofaninja.com");

	startActivity(Intent.createChooser(share, "Share link!"));
}

Step 4: We also have shareImage() method for sharing images. It is triggered when the user clicks on the “Share Image” button.

private void shareImage() {
	Intent share = new Intent(Intent.ACTION_SEND);

	// If you want to share a png image only, you can do:
	// setType("image/png"); OR for jpeg: setType("image/jpeg");
	share.setType("image/*");

	// Make sure you put example png image named myImage.png in your
	// directory
	String imagePath = Environment.getExternalStorageDirectory()
			+ "/myImage.png";

	File imageFileToShare = new File(imagePath);

	Uri uri = Uri.fromFile(imageFileToShare);
	share.putExtra(Intent.EXTRA_STREAM, uri);

	startActivity(Intent.createChooser(share, "Share Image!"));
}

Complete MainActivity.java code:

package com.example.androidshareurlintent;

import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.app.Activity;
import android.content.Intent;

public class MainActivity extends Activity {

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

        // listeners of our two buttons
        View.OnClickListener handler = new View.OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {

                case R.id.buttonShareTextUrl:
                    shareTextUrl();
                    break;

                case R.id.buttonShareImage:
                    shareImage();
                    break;
                }
            }
        };

        // our buttons
        findViewById(R.id.buttonShareTextUrl).setOnClickListener(handler);
        findViewById(R.id.buttonShareImage).setOnClickListener(handler);

    }

    // Method to share either text or URL.
    private void shareTextUrl() {
        Intent share = new Intent(android.content.Intent.ACTION_SEND);
        share.setType("text/plain");
        share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        // Add data to the intent, the receiving app will decide
        // what to do with it.
        share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");
        share.putExtra(Intent.EXTRA_TEXT, "http://www.codeofaninja.com");

        startActivity(Intent.createChooser(share, "Share link!"));
    }

    
    // Method to share any image.
    private void shareImage() {
        Intent share = new Intent(Intent.ACTION_SEND);

        // If you want to share a png image only, you can do:
        // setType("image/png"); OR for jpeg: setType("image/jpeg");
        share.setType("image/*");

        // Make sure you put example png image named myImage.png in your
        // directory
        String imagePath = Environment.getExternalStorageDirectory()
                + "/myImage.png";

        File imageFileToShare = new File(imagePath);

        Uri uri = Uri.fromFile(imageFileToShare);
        share.putExtra(Intent.EXTRA_STREAM, uri);

        startActivity(Intent.createChooser(share, "Share Image!"));
    }

}

Please note that when you use the setType() method, you are enabling Android to filter what apps can share your content. For example, you are sharing a text or URL, the appropriate apps to be shown can be Facebook, Messaging or Email. If you are sharing an image, proper apps can be Instagram, Snapseed or Picasa.

Today’s code output screenshots

android share intent example first run

Main screen.

Android Share Intent - share text or url

Share Text or URL button was touched. Take note of the apps on the list.

android share intent example - User chose to share to Facebook

User chose to share to Facebook

android share image

“Share Image” button was touched. Apps was different on the list.

Android Share Intent - user chose to share with gmail

User chose to share with Gmail. Our image was attached.

Android Share Intent - user chose to share with snapseed

User chose to share to Snapseed.

If you have any suggestions to improve this post, please drop it in the comments section below! I’ll be glad to update this post for further improvement. Thanks for reading our Android Share Intent Example!

Android: Copy Asset To SD Card

Assets folder is where you can store some files for you app. Today I’m going to show you how to copy files from your android app’s asset’s folder to the device SD card. I used this when I have to deploy some default text files for my app and manipulate it at later time. Some existing android applications do this, they create folders with files inside on the first install. You can do the check if the file exists in the directory so you won’t have to copy the assets files every time.
By the way, the assets folder is included in your project package. If you’re using eclipse, you can see it in the package explorer. It looks like this:

An example assets folder. Image from http://goo.gl/ml9UD

An example assets folder. Image from http://goo.gl/ml9UD

In our example our assets has MyHtmlFiles folder with CodeOfANinja.html and ThankYou.html inside. Okay, so now we are going to code the app that:

  1. Copies 2 HTML files from the assets.
  2. Store to the device root directory.

If the HTML files were copied to your SD card, you can now manipulate its contents, rewrite it or make it a dynamic content and show it to your user anytime using the WebView. You can use this code for that.
Download code here:

Download Code

MainActivity.java code

package com.example.assetstosdcard;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.res.AssetManager;

public class MainActivity extends Activity {

    // Buffer size used.
    private final static int BUFFER_SIZE = 1024;

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

        try {
            AssetManager assetFiles = getAssets();

            // MyHtmlFiles is the name of folder from inside our assets folder
            String[] files = assetFiles.list("MyHtmlFiles");

            // Initialize streams
            InputStream in = null;
            OutputStream out = null;

            for (int i = 0; i < files.length; i++) {

                if (files[i].toString().equalsIgnoreCase("images")
                        || files[i].toString().equalsIgnoreCase("js")) {

                    
                     //  @Do nothing. images and js are folders but they will be
                     //  interpreted as files.
                      
                     //  @This is to prevent the app from throwing file not found
                     // exception.
                     

                } else {

                    
                     // @Folder name is also case sensitive
                     // @MyHtmlFiles is the folder from our assets
                     
                    in = assetFiles.open("MyHtmlFiles/" + files[i]);

                    
                     // Currently we will copy the files to the root directory
                     // but you should create specific directory for your app
                     
                    out = new FileOutputStream(
                            Environment.getExternalStorageDirectory() + "/"
                                    + files[i]);
                    copyAssetFiles(in, out);

                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void copyAssetFiles(InputStream in, OutputStream out) {
        try {

            byte[] buffer = new byte[BUFFER_SIZE];
            int read;

            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }

            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

ActivityMain.xml code – This will what will be seen when our the code runs.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="CodeOfANinja.html and ThankYou.html should be copied to the root directory of your SD card by now."
        tools:context=".MainActivity" />

</RelativeLayout>

AndroidManifest.xml code – permission is WRITE_EXTERNAL_STORAGE since we are writing files to SD card.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.assetstosdcard"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

When our code runs:

Check your SD card when you see this.

Check your SD card when you see this.

Thanks for reading this Android: Copy Asset To SD Card!

Android libphonenumber Example

Today I want to show you a simple example code on how to use a very useful library called libphonenumber, a phone number handling library from Google. It can validate the correct number format for your country. In this example we’re using PH (Philippines) as country code. It is optimized for running on smartphones, and is used by the Android framework since 4.0 (Ice Cream Sandwich). Phone number validation is essential for your app so that you can get useful and sound phone numbers from your loyal users. Any verification code, messages or greetings that you want to send them will have lower chances of being missed.

Android libphonenumber Example

Example of a valid cellphone number.

You can download the code here:

DOWNLOAD SOURCE CODE

Online demo here.

Step 1

Download the latest JAR file here. As of this writing, I got libphonenumber-5.2v1.5.jar

Step 2

Copy the JAR file in the libs folder of your project.

libphonenumber

Step 3

Add the JAR on your project. Go to Properties > Java Build Path > Libraries Tab > Click Add Jars.. Button > Browse the JAR file on you libs and click OK. This is what it should look like:

projproperties

Step 4

Our sample XML layout file (activity_main.xml) will have the following code:

<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
   xmlns:tools=“http://schemas.android.com/tools”
   android:layout_width=“match_parent”
   android:layout_height=“match_parent” >
    <EditText
       android:id=“@+id/phoneNumberEditText”
       android:layout_width=“match_parent”
       android:layout_height=“wrap_content”
       android:layout_alignParentLeft=“true”
       android:layout_alignParentTop=“true”
       android:ems=“10″
       android:inputType=“phone” >

        <requestFocus />
    </EditText>

    <Button
       android:id=“@+id/validateButton”
       android:layout_width=“wrap_content”
       android:layout_height=“wrap_content”
       android:layout_alignParentLeft=“true”
       android:layout_below=“@+id/phoneNumberEditText”
       android:text=“Validate Phone Number” />

</RelativeLayout>

Step 5

Our main activity will have the following code:

package com.example.libphonenumber;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

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

        try {
            // so that we can get the inputted phone number
            final EditText et = (EditText) findViewById(R.id.phoneNumberEditText);

            View.OnClickListener handler = new View.OnClickListener() {
                public void onClick(View v) {
                    
                    switch (v.getId()) {

                    // clicking the validate button
                    case R.id.validateButton:

                        // get the inputted phone number
                        String phoneNumber = et.getText().toString();
                        
                        // On our country, people are used to typing 7 (landline) or 11 (cellphone) digit numbers
                        // To make it 7 digit numbers valid, I have to prepend “02″
                        if (phoneNumber.length() == 7) {
                            phoneNumber = “02″ + phoneNumber;
                        }

                        // Use the library’s functions
                        PhoneNumberUtil phoneUtil = PhoneNumberUtil
                                .getInstance();
                        PhoneNumber phNumberProto = null;

                        try {

                            // I set the default region to PH (Philippines)
                            // You can find your country code here http://www.iso.org/iso/country_names_and_code_elements
                            phNumberProto = phoneUtil.parse(phoneNumber, “PH”);

                        } catch (NumberParseException e) {
                            // if there’s any error
                            System.err
                                    .println(“NumberParseException was thrown: “
                                            + e.toString());
                        }

                        // check if the number is valid
                        boolean isValid = phoneUtil
                                .isValidNumber(phNumberProto);

                        if (isValid) {

                            // get the valid number’s international format
                            String internationalFormat = phoneUtil.format(
                                    phNumberProto,
                                    PhoneNumberFormat.INTERNATIONAL);

                            Toast.makeText(
                                    getBaseContext(),
                                    “Phone number VALID: “ + internationalFormat,
                                    Toast.LENGTH_SHORT).show();

                        } else {

                            // prompt the user when the number is invalid
                            Toast.makeText(
                                    getBaseContext(),
                                    “Phone number is INVALID: “ + phoneNumber,
                                    Toast.LENGTH_SHORT).show();

                        }

                        break;

                    }
                }
            };

            // we will set the listeners
            findViewById(R.id.validateButton).setOnClickListener(handler);

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Sample Output: (I felt like my phone is too small so I tested it on my tablet haha!)

An example of a valid land line number.

An example of a valid land line number.

Example of an invalid land line number.

Example of an invalid land line number.

Example of an invalid cellphone number.

Example of an invalid cellphone number.

That’s it! Happy New Year guys! :)

Android Camera Code Tutorial

Today we are going to do a code that can enable your android application to capture images using the device camera. In this example code, we will have:

  1. A “Take Picture” button on our main activity, when the user clicks it, the device camera will be shown that will enable your user the take a picture.
  2. After taking a picture, the preview of the image will be shown with options to “Save” or “Discard” the image.
  3. If the user tapped “Save”, the image will be saved on the directory we specified in our code, else, if the user tapped “Discard”, the device camera will be shown again.
  4. If the user saved the image, he will be asked if he wants to take another picture.

Android Camera Code Tutorial

DOWNLOAD SOURCE CODE

Our MainActivity.java code – This activity will show our “Take Picture” button.

package com.example.camerahelper;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;

public class MainActivity extends Activity {

    Context mContext;

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

        mContext = MainActivity.this;

        View.OnClickListener handler = new View.OnClickListener() {
            public void onClick(View v) {

                switch (v.getId()) {

                case R.id.takePicture:
                    // go to camera activity
                    Intent nextActivity = new Intent(mContext,
                            CameraActivity.class);
                    startActivity(nextActivity);
                    break;

                }
            }
        };

        findViewById(R.id.takePicture).setOnClickListener(handler);

    }

}

Our res/layout/activity_main.xml – The XML layout file for our MainActivity.

<?xml version=“1.0″ encoding=“utf-8″?>
<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
   android:id=“@+id/widget29″
   android:layout_width=“fill_parent”
   android:layout_height=“fill_parent” >
    <Button
       android:id=“@+id/takePicture”
       android:layout_width=“wrap_content”
       android:layout_height=“wrap_content”
       android:layout_centerHorizontal=“true”
       android:layout_centerVertical=“true”
       android:text=“@string/take_picture” />

</RelativeLayout>

Our CameraActivity.java – This code does almost all the operations from starting the device camera to saving the image to specified directory.

package com.example.camerahelper;
import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

public class CameraActivity extends Activity {

    private static final String LOG_TAG = “CameraActivity.java”;
    private static final int IMAGE_CAPTURE = 0;

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

        try {

            // intent to start device camera
            Intent intent = new Intent(“android.media.action.IMAGE_CAPTURE”);

            // you can also create your own filename or path
            String fileName = “codeofaninja_app”;

            // where do you want to save the images
            String path = Environment.getExternalStorageDirectory() + “/”
                    + fileName + “.jpg”;

            File file = new File(path);

            // if the file name already exists, append __x on the file name
            int x = 2;
            while (file.exists()) {

                path = Environment.getExternalStorageDirectory() + “/”
                        + fileName + “__” + x + “.jpg”;
                file = new File(path);

                x++;
            }

            Uri outputFileUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

            // 0, this code will be returned in onActivityResult() when the
            // activity exits.
            startActivityForResult(intent, 0);

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // activity exits
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (requestCode == IMAGE_CAPTURE) {
                if (resultCode == RESULT_OK) {

                    Log.v(LOG_TAG, “Picture taken.”);

                    // delete last image from dcim
                    if(!deleteLastSavedDcimImage()){
                        Log.v(LOG_TAG,“Unable to delete last saved image in /Camera/DCIM/”);
                    }

                    // ask if the user want’s to take another picture
                    takeAnother();

                } else {
                    // you can specify any message here
                    // or just remove it
                    Toast.makeText(getBaseContext(),
                            “Error: Result code is not RESULT_OK.”,
                            Toast.LENGTH_SHORT).show();

                }
            } else {
                // you can specify any message here
                // or just remove it
                Toast.makeText(getBaseContext(),
                        “Error: Request code is not IMAGE_CAPTURE.”,
                        Toast.LENGTH_SHORT).show();
            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        CameraActivity.this.finish();
    }

    public void takeAnother() {
        try {

            new AlertDialog.Builder(this).setTitle(“The Code Of A Ninja”)
                    .setMessage(“Do you want to take another picture?”)
                    .setPositiveButton(“YES”, new OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                            arg0.dismiss();

                            Intent nextActivity = new Intent(
                                    CameraActivity.this, CameraActivity.class);
                            CameraActivity.this.finish();
                            startActivity(nextActivity);

                        }
                    })

                    .setNegativeButton(“NO”, new OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {

                            arg0.dismiss();

                            Toast.makeText(CameraActivity.this,
                                    “Done taking picture.”, Toast.LENGTH_LONG)
                                    .show();

                            // go to main activity
                            CameraActivity.this.finish();

                        }
                    }).show();

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // since our code also saves the taken images to DCIM/Camera folder of the
    // device, we have to delete it there so that the image will be saved
    // only to the directory we have specified.
    private boolean deleteLastSavedDcimImage() {

        Log.v(LOG_TAG, “Deleting late image from DCIM.”);

        boolean success = false;

        try {

            // list the images in the device /DCIM/Camera directory
            File[] images = new File(Environment.getExternalStorageDirectory()
                    + “/DCIM/Camera”).listFiles();
            File lastSavedImage = images[0];
            int imagesLen =  images.length;
            
            //loop and check for the last modified image to get the last save image
            for (int i = 1; i < imagesLen; ++i) {
                if (images[i].lastModified() > lastSavedImage.lastModified()) {
                    lastSavedImage = images[i];
                }
            }

            //then delete the last saved image
            success = new File(lastSavedImage.toString()).delete();

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return success;
    }
}

Our res/layout/camera.xml code – XML I used for our CameraActivity.java activity

<?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” >
    <TextView
       android:id=“@+id/textView1″
       android:layout_width=“wrap_content”
       android:layout_height=“wrap_content”
       android:text=“” >
    </TextView>

</LinearLayout>

The AndroidManifest.xml code – This will give us permission to use the device camera hardware.

<manifest xmlns:android=“http://schemas.android.com/apk/res/android”
   package=“com.example.camerahelper”
   android:versionCode=“1″
   android:versionName=“1.0″ >
    <uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE” />
    <uses-permission android:name=“android.permission.CAMERA” />

    <uses-feature android:name=“android.hardware.camera” />
    <uses-feature android:name=“android.hardware.camera.autofocus” />

    <uses-sdk
       android:minSdkVersion=“8″
       android:targetSdkVersion=“15″ />

    <application
       android:icon=“@drawable/ic_launcher”
       android:label=“@string/app_name”
       android:theme=“@style/AppTheme” >
        <activity
           android:name=“.MainActivity”
           android:label=“@string/title_activity_main” >
            <intent-filter>
                <action android:name=“android.intent.action.MAIN” />

                <category android:name=“android.intent.category.LAUNCHER” />
            </intent-filter>
        </activity>
        <activity android:name=“.CameraActivity” >
        </activity>
    </application>

</manifest>

Some output screenshots:

11

22

33

Android Webview Example Code

Hi there! Today I’m gonna share how to view a website or webpage to your Android apllication. You’ll be able to view webpages from the internet or from the storage of your Adroid device such as your sdcard. This is useful if you want your app not to open a web browser for web links. It is like, the browser is inside or embedded your Android application.

Android Webview Example Code

Android WebView

The following code will enable you to view this blog on your Android Application. This code uses the Android WebView class which is also an extension of Android’s View class.

package com.example.yourproject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class YourProject extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          //setContentView(R.layout.main);
        
          // Let's display the progress in the activity title bar, like the
          // browser app does.
          getWindow().requestFeature(Window.FEATURE_PROGRESS);

          WebView webview = new WebView(this);
          setContentView(webview);
        
          webview.getSettings().setJavaScriptEnabled(true);

          final Activity activity = this;
          webview.setWebChromeClient(new WebChromeClient() {
          public void onProgressChanged(WebView view, int progress) {
               // Activities and WebViews measure progress with different scales.
               // The progress meter will automatically disappear when we reach 100%
               activity.setProgress(progress * 1000);
          }
        });
        
webview.setWebViewClient(new WebViewClient() {
          
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
          //Users will be notified in case there's an error (i.e. no internet connection)
          Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
 });
       //This will load the webpage that we want to see
        webview.loadUrl("http://codeofaninja.blogspot.com/");

     }
}

If you want to view an html page from your sdcard, you can change the url for example “file:///sdcard/YourProject/index.html“. Well that’s it. Thanks for reading. :)

DOWNLOAD SOURCE CODE

Resources:
http://developer.android.com/guide/webapps/webview.html
http://developer.android.com/reference/android/webkit/WebView.html

Instant Android Webview Code

Hi guys! Today I want to share a class I created to help me whenever I have a WebView activity in my app. I simply call it a WebView helper class. The main benefit of having a class like this for your web views is that, you won’t have to specify the same code over and over again for each of your web view activities. You are re-using the web view code that shortens and make our code look cleaner. You can just use one settings for all your web views, and at the same time, you can add any JavaScript interfaces and specify the URL to be loaded.

What loading pages will look like.

What loading pages will look like.

How to use?

For the sake of starting android programmers, I will include the whole code of our MainActivity:

package com.codeofaninja.app;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.webkit.WebView;
public class MainActivity extends Activity {

     WebView web;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      
        // initialize our helper class
        // then call the webview() methods with our context as parameter (MainActivity.this)
        web = new WebViewHelper().webview(MainActivity.this);
      
        // specify the url we want to load
        web.loadUrl(“http://codeofaninja.com/”);
      
        // you can add JavaScript interface like this:
        // web.addJavascriptInterface(new YourJsInterfaceClass(), “Android”);

        // set web as content view
        setContentView(web);
      
    }
  
}

Our WebViewHelper.java code:

package code.of.a.ninja.Utils;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.widget.Toast;

public class WebViewHelper {

    private ProgressDialog mProgressDialog;

    //make it final so it will be accessible to setWebViewClient
    public WebView webview(final Context mContext) {

        // progress dialog
        mProgressDialog = new ProgressDialog(mContext);

        // new webview
        WebView web = new WebView(mContext);

        // web settings
        WebSettings webSettings = web.getSettings();

        // false
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setAppCacheEnabled(false);

        // true
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);

        // other
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setRenderPriority(RenderPriority.HIGH);

        web.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                //show the user progress percentage
                mProgressDialog.setMessage(“Loading… “ + progress + “%”);
            }
        });

        web.setWebViewClient(new WebViewClient() {

            public void onReceivedError(WebView view, int errorCode,
                    String description, String failingUrl) {

                //if there’s an error loading the page, make a toast
                Toast.makeText(mContext, description + “.”, Toast.LENGTH_SHORT)
                        .show();

            }

            public void onPageFinished(WebView view, String url) {
                //after loading page, remove loading page
                mProgressDialog.dismiss();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);

                //on page started, show loading page
                mProgressDialog.setCancelable(false);
                mProgressDialog.setMessage(“Loading…”);
                mProgressDialog.show();

            }

        });

        // return the web view
        return web;
    }
}

That’s it! Enjoy using our web view helper class!

Verify if Java was Installed in Ubuntu 11.10

Ubuntu Quick Tip: After my JDK installation, I wanted to verify if it was really installed in my computer. Here’s how I verified it

1. Run your terminal.

2. Type:

          $ sudo updatedb
          $ locate java
  • It asked me to enter my password after typing sudo updatedb.
  • updatedb means you are updating the database for locate or locating your app.
  • locate finds files by name.
Verify if Java was Installed in Ubuntu 11.10
Click to enlarge.

3. If it returns something like this:

Click to enlarge.

it means JDK was installed.

Android Download File With Progress Bar Example

Hi guys! Today we are going to do a script that will show an Android progress bar while downloading a file. A progress bar looks good for the user to be notified about the progress of the download.
We will easily use a UI thread with Android AsyncTask. In other terms, we will use a subclass to handle our downloader thread.

Our output is something like this

Our output is something like this

DownloadFile.java

package com.example.downloadfile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class DownloadFile extends Activity {
    
    public static final String LOG_TAG = “Android Downloader by The Code Of A Ninja”;
    
    //initialize our progress dialog/bar
    private ProgressDialog mProgressDialog;
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    
    //initialize root directory
    File rootDir = Environment.getExternalStorageDirectory();
    
    //defining file name and url
    public String fileName = “codeofaninja.jpg”;
    public String fileURL = “https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG”;
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        //setting some display
        setContentView(R.layout.main);
        TextView tv = new TextView(this);
        tv.setText(“Android Download File With Progress Bar”);
    
        //making sure the download directory exists
        checkAndCreateDirectory(“/my_downloads”);
        
        //executing the asynctask
        new DownloadFileAsync().execute(fileURL);
    }
  
    //this is our download file asynctask
    class DownloadFileAsync extends AsyncTask<String, String, String> {
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        
        @Override
        protected String doInBackground(String… aurl) {

            try {
                //connecting to url
                URL u = new URL(fileURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod(“GET”);
                c.setDoOutput(true);
                c.connect();
                
                //lenghtOfFile is used for calculating download progress
                int lenghtOfFile = c.getContentLength();
                
                //this is where the file will be seen after the download
                FileOutputStream f = new FileOutputStream(new File(rootDir + “/my_downloads/”, fileName));
                //file input is from the url
                InputStream in = c.getInputStream();

                //here’s the download code
                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;
                
                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress(“” + (int)((total*100)/lenghtOfFile));
                    f.write(buffer, 0, len1);
                }
                f.close();
                
            } catch (Exception e) {
                Log.d(LOG_TAG, e.getMessage());
            }
            
            return null;
        }
        
        protected void onProgressUpdate(String… progress) {
             Log.d(LOG_TAG,progress[0]);
             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) {
            //dismiss the dialog after the file was downloaded
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    }
    
    //function to verify if directory exists
    public void checkAndCreateDirectory(String dirName){
        File new_dir = new File( rootDir + dirName );
        if( !new_dir.exists() ){
            new_dir.mkdirs();
        }
    }
    
    //our progress bar settings
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage(“Downloading file…”);
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }
}

And for the AndroidManifest.xml, include the INTERNET and WRITE_EXTERNAL_STORAGE permissions.

<?xml version=“1.0″ encoding=“utf-8″?>
<manifest xmlns:android=“http://schemas.android.com/apk/res/android”
     package=“com.example.downloadfile”
     android:versionCode=“1″
     android:versionName=“1.0″>
      
    <uses-permission android:name=“android.permission.INTERNET” />
    <uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE” />
      
    <uses-sdk android:minSdkVersion=“4″ />
    <application android:icon=“@drawable/icon” android:label=“@string/app_name”>
        <activity android:name=“.DownloadFile”
                 android:label=“@string/app_name”>
            <intent-filter>
                <action android:name=“android.intent.action.MAIN” />
                <category android:name=“android.intent.category.LAUNCHER” />
            </intent-filter>
        </activity>

    </application>
</manifest>

Thanks for reading this Android Download File With Progress Bar Example!

Center Screen Two Android Buttons

Recently I was into a problem when I was unable to center screen two Android buttons, in a simplest way. My Google skills failed me to find a simple way, so I had to figure it out myself. I wanted my buttons to be centered horizontally and vertically on the screen. And those buttons would have certain widths. Like this one:

Center Screen Two Android Buttons

Centered Two Android Buttons

I got it by using these codes:

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

    <LinearLayout 
    android:orientation="horizontal"
    android:layout_width="400dp"
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true">
    
        <Button 
        android:id="@+id/messagesBtn" 
        android:layout_width="0.0dip"
        android:layout_height="fill_parent" 
        android:text="Lovely Button"
        android:layout_weight="1.0" />
        
        <Button 
        android:id="@+id/performanceSummaryBtn" 
        android:layout_width="0.0dip"
        android:layout_height="fill_parent" 
        android:text="Sweet Button"
        android:layout_weight="1.0" />
        
    </LinearLayout>
    
</RelativeLayout>

That’s it! :)