Android Custom ListView Tutorial

Almost all Android apps uses ListView – showing list of records, settings, songs, articles, and many other types of data a certain app can handle. An Android ListView is simply a vertically scrollable list of items.This tutorial will show you how to create a customized row in your ListView (with image and text). This is probably the simplest android ListView tutorial on the internet. Haha!
I remember using a ListView when I have to list records of location with its thumbnail, location name and date the data were taken.

Upper part of our ListView

Upper part of our ListView

Anyway, we are going to have Folders as our items on the list. Our code will have the following capability:

  • Include custom folder icon, folder name and description for each list item.
  • Show a toast when a user clicks on an item on the list (means we’re going to have an onClickListener)

Code Download

You can download the code here: (If you’re not familiar with Google Drive, you have to click on File > Download to download the code)
Download Code

Files Needed

We are going to need only 2 JAVA files, 2 XML files and 3 custom icons.

Highlighted are the files we’ll create.

Highlighted are the files we’ll create.

Let’s Code!

activity_main.xml – Contains our ListView.

<?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:background="#FFFFFF"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

listview_item_row.xml – the layout of each list item in our list view.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/imageViewFolderIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:paddingRight="10dp"
        android:src="@drawable/folder" />

    <TextView
        android:id="@+id/textViewFolderName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/imageViewFolderIcon"
        android:text="Folder name here."
        android:textSize="20dp" />

    <TextView
        android:id="@+id/textViewFolderDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewFolderName"
        android:layout_toRightOf="@+id/imageViewFolderIcon"
        android:text="Folder description here."
        android:textColor="#c5c5c5"
        android:textSize="14dp" />

</RelativeLayout>

It will look like this:

android-listview-tutorial-listiem-layout

-Folder Icon
android:id=”@+id/imageViewFolderIcon”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true”

-Folder Name
android:id=”@+id/textViewFolderName”
android:layout_alignParentTop=”true”
android:layout_toRightOf=”@+id/imageViewFolderIcon”

-Folder Description
android:id=”@+id/textViewFolderDescription”
android:layout_below=”@+id/textViewFolderName”
android:layout_toRightOf=”@+id/imageViewFolderIcon”

MainActivity.java – We have two classes in this file, first is the MainActivity where we set each of our list item data and second is the small Folder class that will take care of our list item data such as the folderIcon, folderName and folderDescription.

package com.example.androidlistview;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

    private ListView listViewArticles;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        
         // Data can be from your database. You have to know the number of list
         // items in advanced, in our example, we have 9
         
         
        Folder[] folderData = new Folder[27];

        
         // @always start with index 0
          
          // @9 items in our list view.
         

        folderData[0] = new Folder(R.drawable.icon_music_folder, "Usher", "My most favorite Usher songs.");
        folderData[1] = new Folder(R.drawable.icon_pictures_folder, "Family Images", "Pictures from different occasions.");
        folderData[2] = new Folder(R.drawable.icon_spreadsheet_folder, "Budget Spreadsheet", "My budget record every week.");
        folderData[3] = new Folder(R.drawable.icon_music_folder, "FM Static", "One of my most favorite bands.");
        folderData[4] = new Folder(R.drawable.icon_pictures_folder, "Outing - 2012", "Pictures in Boracay Island.");
        folderData[5] = new Folder(R.drawable.icon_spreadsheet_folder, "Business Spreadsheet", "Business accounts record.");
        folderData[6] = new Folder(R.drawable.icon_music_folder, "New Artists", "Cool songs by new artists.");
        folderData[7] = new Folder(R.drawable.icon_pictures_folder, "Anniversary - 2012", "Company party.");
        folderData[8] = new Folder(R.drawable.icon_spreadsheet_folder, "Credit Spreadsheet", "Credit records every month.");

        folderData[9] = new Folder(R.drawable.icon_music_folder, "Usher - 2", "My most favorite Usher songs - 2.");
        folderData[10] = new Folder(R.drawable.icon_pictures_folder, "Family Images - 2", "Pictures from different occasions - 2.");
        folderData[11] = new Folder(R.drawable.icon_spreadsheet_folder, "Budget Spreadsheet - 2", "My budget record every week - 2.");
        folderData[12] = new Folder(R.drawable.icon_music_folder, "FM Static - 2", "One of my most favorite bands - 2.");
        folderData[13] = new Folder(R.drawable.icon_pictures_folder, "Outing - 2012 - 2", "Pictures in Boracay Island - 2.");
        folderData[14] = new Folder(R.drawable.icon_spreadsheet_folder, "Business Spreadsheet - 2", "Business accounts record - 2.");
        folderData[15] = new Folder(R.drawable.icon_music_folder, "New Artists - 2", "Cool songs by new artists - 2.");
        folderData[16] = new Folder(R.drawable.icon_pictures_folder, "Anniversary - 2012 - 2", "Company party - 2.");
        folderData[17] = new Folder(R.drawable.icon_spreadsheet_folder, "Credit Spreadsheet - 2", "Credit records every month - 2.");
        
        folderData[18] = new Folder(R.drawable.icon_music_folder, "Usher - 3", "My most favorite Usher songs - 3.");
        folderData[19] = new Folder(R.drawable.icon_pictures_folder, "Family Images - 3", "Pictures from different occasions - 3.");
        folderData[20] = new Folder(R.drawable.icon_spreadsheet_folder, "Budget Spreadsheet - 3", "My budget record every week - 3.");
        folderData[21] = new Folder(R.drawable.icon_music_folder, "FM Static - 3", "One of my most favorite bands - 3.");
        folderData[22] = new Folder(R.drawable.icon_pictures_folder, "Outing - 2012 -3", "Pictures in Boracay Island - 3.");
        folderData[23] = new Folder(R.drawable.icon_spreadsheet_folder, "Business Spreadsheet - 3", "Business accounts record - 3.");
        folderData[24] = new Folder(R.drawable.icon_music_folder, "New Artists - 3", "Cool songs by new artists - 3.");
        folderData[25] = new Folder(R.drawable.icon_pictures_folder, "Anniversary - 2012 - 3", "Company party - 3.");
        folderData[26] = new Folder(R.drawable.icon_spreadsheet_folder, "Credit Spreadsheet - 3", "Credit records every month - 3.");
        
        // Pass the folderData to our ListView adapter 
        FolderAdapter adapter = new FolderAdapter(this,
                R.layout.listview_item_row, folderData);

        // Set the adapter to our ListView
        listViewArticles = (ListView) findViewById(R.id.listView1);
        listViewArticles.setAdapter(adapter);

        
        // ListView item click listener. So we'll have the do stuff on click of
        // our ListItem
         
        listViewArticles.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                // get the clicked folder name
                String listItemText = ((TextView) view
                        .findViewById(R.id.textViewFolderName))
                        .getText()
                        .toString();

                // just toast it
                Toast.makeText(MainActivity.this,
                        "You clicked: " + listItemText, Toast.LENGTH_LONG)
                        .show();

                // if you want to show a new screen or activity, you can call the intent here
            }
        });
    }

    
    // You can put this in another java file. This will hold the data elements
    // of our list item.
    
    class Folder {

        public int folderIcon;
        public String folderName;
        public String folderDescription;

        // Constructor.
        public Folder(int folderIcon, String folderName,
                String folderDescription) {

            this.folderIcon = folderIcon;
            this.folderName = folderName;
            this.folderDescription = folderDescription;
        }
    }
}

FolderAdapter.java – This file will make the list items come true. We’ll override the getView to set our customized data.

package com.example.androidlistview;

import com.example.androidlistview.MainActivity.Folder;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class FolderAdapter extends ArrayAdapter<Folder> {

    Context mContext;
    int layoutResourceId;
    Folder data[] = null;

   
     // @mContext - app context
      
     // @layoutResourceId - the listview_item_row.xml
      
     // @data - the ListItem data
     
    public FolderAdapter(Context mContext, int layoutResourceId, Folder[] data) {

        super(mContext, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.mContext = mContext;
        this.data = data;
    }

    
     // @We'll overried the getView method which is called for every ListItem we have.
      
     // @There are lots of different caching techniques for Android ListView to
     // achieve better performace especially if you are going to have a very long ListView.
      
     // @convertView - the cache of list item row layout, if it is null, inflate new
     
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(convertView==null){
            // inflate the listview_item_row.xml parent
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
            convertView = inflater.inflate(layoutResourceId, parent, false);
        }
        
        // get the elements in the layout
        ImageView imageViewFolderIcon = (ImageView) convertView.findViewById(R.id.imageViewFolderIcon);
        TextView textViewFolderName = (TextView) convertView.findViewById(R.id.textViewFolderName);
        TextView textViewFolderDescription = (TextView) convertView.findViewById(R.id.textViewFolderDescription);

        
        // Set the data for the list item. You can also set tags here if you want.
         
        Folder folder = data[position];

        imageViewFolderIcon.setImageResource(folder.folderIcon);
        textViewFolderName.setText(folder.folderName);
        textViewFolderDescription.setText(folder.folderDescription);

        return convertView;
    }

}

Output Screenshots

Lower part of our ListView

Lower part of our ListView


When user clicks on an item “Budget Spreadsheet”

When user clicks on an item
“Budget Spreadsheet”

Further Readings

If you’re loading your images from the internet, you might want to lazy load them for better ListView performance. You can use a library called LazyList.

If you want to see code example which focuses a bit on the adapter, see this post: Android ListView with Adapter Example

Thanks for reading this Android Custom ListView Tutorial!

Android XML Parser Example with XML from SD Card, URL or Assets

XML parsing could be one of the most basic requirement on your Android application. In today’s tutorial, we are going to read XML files using three input sources. There can be three sources of your XML:

1. XML from device SD Card. Your dynamic XML file could be downloaded first for offline use.
2. XML from a URL. You could be parsing data from your online database or RSS feed. Works if device is online only.
3. XML from your app’s assets folder. Your XML file is not dynamic so it is better to put it in the asset’s folder where it cannot be change.

By the way, we’ll be using SAX parser here. I think that for mobile apps, SAX parser is better to use than DOM parser.

DOM parser consumes more memory because it loads the whole XML data to the device memory while SAX parser does an event driven approach. SAX parser processes each line of the XML without loading it to the device memory first.

xml-parsing-tutorial-output

DOWNLOAD SOURCE CODE HERE

Our XML structure looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<Contents>
    <Owners>
        <Owner>
            <Name>Joselito Dimaculangan</Name>
            <Age>16</Age>
            <EmailAddress>joselito123@gmail.com</EmailAddress>
        </Owner>
        <Owner>
            <Name>Noemi De Galileo</Name>
            <Age>14</Age>
            <EmailAddress>noemi111@gmail.com</EmailAddress>
        </Owner>
    </Owners>
    <Dogs>
        <Dog>
            <Name>Barky</Name>
            <Birthday>June 29, 2012</Birthday>
        </Dog>
        <Dog>
            <Name>Jumbo</Name>
            <Birthday>December 30, 2012</Birthday>
        </Dog>
    </Dogs>
</Contents>

MainActivity.java code – Here you can change the value of x to 1,2 or 3 to change the input source. Read comments on code.

package com.example.androidparsexml;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.app.Activity;

public class MainActivity extends Activity {

    public static final String LOG_TAG = "MainActivity.java";

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

        try {

            // parse our XML
            new parseXmlAsync().execute();

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

    /*
     * @We are using an AsyncTask to avoid
     * android.os.NetworkOnMainThreadException when parsing from a URL
     *
     * @If you don't know a thing about AsyncTasks,there are a lot of excellent
     * tutorial out there, see this thread
     */
    private class parseXmlAsync extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... strings) {

            try {

                /*
                 * You may change the value of x to try different sources of XML
                 *
                 * @1 = XML from SD Card
                 *
                 * @2 = XML from URL
                 *
                 * @3 = XML from assets folder
                 */
                int x = 2;

                // initialize our input source variable
                InputSource inputSource = null;

                // XML from sdcard
                if (x == 1) {

                    // make sure sample.xml is in your root SD card directory
                    File xmlFile = new File(
                            Environment.getExternalStorageDirectory()
                                    + "/sample.xml");
                    FileInputStream xmlFileInputStream = new FileInputStream(
                            xmlFile);
                    inputSource = new InputSource(xmlFileInputStream);
                }

                // XML from URL
                else if (x == 2) {
                    // specify a URL
                    // make sure you are connected to the internet
                    URL url = new URL(
                            "http://demo.codeofaninja.com/AndroidXml/sample.xml");
                    inputSource = new InputSource(url.openStream());
                }

                // XML from assets folder
                else if (x == 3) {
                    inputSource = new InputSource(getAssets()
                            .open("sample.xml"));
                }

                // instantiate SAX parser
                SAXParserFactory saxParserFactory = SAXParserFactory
                        .newInstance();
                SAXParser saxParser = saxParserFactory.newSAXParser();

                // get the XML reader
                XMLReader xmlReader = saxParser.getXMLReader();

                // prepare and set the XML content or data handler before
                // parsing
                XmlContentHandler xmlContentHandler = new XmlContentHandler();
                xmlReader.setContentHandler(xmlContentHandler);

                // parse the XML input source
                xmlReader.parse(inputSource);

                // put the parsed data to a List
                List<ParsedDataSet> parsedDataSet = xmlContentHandler
                        .getParsedData();

                // we'll use an iterator so we can loop through the data
                Iterator<ParsedDataSet> i = parsedDataSet.iterator();
                ParsedDataSet dataItem;

                while (i.hasNext()) {

                    dataItem = (ParsedDataSet) i.next();

                    /*
                     * parentTag can also represent the main type of data, in
                     * our example, "Owners" and "Dogs"
                     */
                    String parentTag = dataItem.getParentTag();
                    Log.v(LOG_TAG, "parentTag: " + parentTag);

                    if (parentTag.equals("Owners")) {
                        Log.v(LOG_TAG, "Name: " + dataItem.getName());
                        Log.v(LOG_TAG, "Age: " + dataItem.getAge());
                        Log.v(LOG_TAG,
                                "EmailAddress: " + dataItem.getEmailAddress());
                    }

                    else if (parentTag.equals("Dogs")) {
                        Log.v(LOG_TAG, "Name: " + dataItem.getName());
                        Log.v(LOG_TAG, "Birthday: " + dataItem.getBirthday());
                    }

                }

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

        @Override
        protected void onPostExecute(String lenghtOfFile) {
            // your do stuff after parsing the XML
        }
    }

}

XmlContentHandler.java – We’ll extend the default handler.

package com.example.androidparsexml;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class XmlContentHandler extends DefaultHandler {

    private static final String LOG_TAG = "XmlContentHandler";

    // used to track of what tags are we
    private boolean inOwner = false;
    private boolean inDog = false;

    // accumulate the values
    private StringBuilder mStringBuilder = new StringBuilder();

    // new object
    private ParsedDataSet mParsedDataSet = new ParsedDataSet();

    // the list of data
    private List<ParsedDataSet> mParsedDataSetList = new ArrayList<ParsedDataSet>();

    /*
     * Called when parsed data is requested.
     */
    public List<ParsedDataSet> getParsedData() {
        Log.v(LOG_TAG, "Returning mParsedDataSetList");
        return this.mParsedDataSetList;
    }

    // Methods below are built in, we just have to do the tweaks.

    /*
     * @Receive notification of the start of an element.
     *
     * @Called in opening tags such as <Owner>
     */
    @Override
    public void startElement(String namespaceURI, String localName,
            String qName, Attributes atts) throws SAXException {

        if (localName.equals("Owner")) {
            // meaning new data object will be made
            this.mParsedDataSet = new ParsedDataSet();
            this.inOwner = true;
        }

        else if (localName.equals("Dog")) {
            this.mParsedDataSet = new ParsedDataSet();
            this.inDog = true;
        }

    }

    /*
     * @Receive notification of the end of an element.
     *
     * @Called in end tags such as </Owner>
     */
    @Override
    public void endElement(String namespaceURI, String localName, String qName)
            throws SAXException {

        // Owners
        if (this.inOwner == true && localName.equals("Owner")) {
            this.mParsedDataSetList.add(mParsedDataSet);
            mParsedDataSet.setParentTag("Owners");
            this.inOwner = false;
        }

        else if (this.inOwner == true && localName.equals("Name")) {
            mParsedDataSet.setName(mStringBuilder.toString().trim());
        }

        else if (this.inOwner == true && localName.equals("Age")) {
            mParsedDataSet.setAge(mStringBuilder.toString().trim());
        }

        else if (this.inOwner == true && localName.equals("EmailAddress")) {
            mParsedDataSet.setEmailAddress(mStringBuilder.toString().trim());
        }

        // Dogs
        if (this.inDog == true && localName.equals("Dog")) {
            this.mParsedDataSetList.add(mParsedDataSet);
            mParsedDataSet.setParentTag("Dogs");
            this.inDog = false;
        }

        else if (this.inDog == true && localName.equals("Name")) {
            mParsedDataSet.setName(mStringBuilder.toString().trim());
        }

        else if (this.inDog == true && localName.equals("Birthday")) {
            mParsedDataSet.setBirthday(mStringBuilder.toString().trim());
        }

        // empty our string builder
        mStringBuilder.setLength(0);
    }

    /*
     * @Receive notification of character data inside an element.
     *
     * @Gets be called on the following structure: <tag>characters</tag>
     */
    @Override
    public void characters(char ch[], int start, int length) {
        // append the value to our string builder
        mStringBuilder.append(ch, start, length);
    }
}

ParsedDataSet.java – You can use your own object class if the XML you’re parsing is for a more specific data object. For example, you are parsing only for “Owners” and NOT “Owners & Dogs” like what we have.

package com.example.androidparsexml;

public class ParsedDataSet {

	private String parentTag = null;
	private String name = null;
	private String age = null;
	private String emailAddress = null;
	private String birthday = null;

	// parent tag
	public String getParentTag() {
		return parentTag;
	}

	public void setParentTag(String parentTag) {
		this.parentTag = parentTag;
	}

	// name
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	// age
	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	// emailAddress
	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	// birthday
	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String name) {
		this.birthday = name;
	}
}

Our AndroidManifest.xml will have internet permissions because we use a URL input

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

Our code output on the device look simply like this:

Device output.

Ways to Create a Splash Screen for Android App

Today we’re going to create a splash screen for your Android app. A splash screen is usually an image or a view that appears to the user while the app is loading, it is also a way to make your brand or logo easier to be recognize by the user. Some android apps that uses splash screens include Facebook, Pocket and of course, the game apps. I’m going to show you two ways to create android splash screens.

Example logo to be seen in our splash screen.

Example logo to be seen in our splash screen.

Splash Screen With Two Activities

The first way I’m gonna teach you is using two activities, the first activity will be our splash screen and the second activity will be our app’s main screen. The splash screen activity will be shown for four seconds and then it will show the next activity. Download the code here:

Download Code

Here are the files we need:

Highlighted are the files we have to create.

Highlighted are the files we have to create.

SplashScreenActivity.java – The initial activity executed. This activity will end with an animation that depends on the device.

        // remove title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // our layout xml
        setContentView(R.layout.activity_splash_screen);

        // we're gonna use a timer task to show the main activity after 4 seconds
        TimerTask task = new TimerTask() {

            @Override
            public void run() {

                // go to the main activity
                Intent nextActivity = new Intent(SplashScreenActivity.this,
                        MainActivity.class);
                startActivity(nextActivity);

                // make sure splash screen activity is gone
                SplashScreenActivity.this.finish();

            }

        };

        // Schedule a task for single execution after a specified delay.
        // Show splash screen for 4 seconds
        new Timer().schedule(task, 4000);

    }

}

MainActivity.java – Our app’s main screen, where the main functions of your app should be seen.

package com.example.splashscreenexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // remove title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        // our main activity layout
        setContentView(R.layout.activity_main);
        
    }
}

codeofaninja350pxwidth.png – An example image used in the splash screen. This is included in the code download.

Splash Screen with One Activity

The second way to create a splash screen is using just one activity – your MainActivity. It should be covered with an ImageView first and then after few seconds, it will disappear with a simple fade-out animation to make it look smooth. Download code this code:

Download Code

Files we need are highlighted below:

We’ll work on three files in this example.

We’ll work on three files in this example.

MainActivitity.java – The file with double purpose, it will show our splash screen and then main screen.

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class MainActivity extends Activity {

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

        // remove title bar.
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);

        // our timer task.
        TimerTask task = new TimerTask() {

            @Override
            public void run() {

                // we have to run it on UI thread so we won't get view error
                MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {

                        // get the splash image
                        ImageView splashImage = (ImageView) MainActivity.this
                                .findViewById(R.id.imageViewSplashLogo);
                        
                        // make the splash image invisible
                        splashImage.setVisibility(View.GONE);

                        // specify animation
                        Animation animFadeOut = AnimationUtils.loadAnimation(MainActivity.this,
                                R.anim.splash_screen_fadeout);
                        
                        // apply the animattion
                        splashImage.startAnimation(animFadeOut);
                        
                    }
                });

            }

        };

        // Schedule a task for single execution after a specified delay.
        // Show splash screen for 4 seconds
        new Timer().schedule(task, 4000);

    }

}

splash_screen_fadeout.xml – It will make our splash screen gone beautifully – a simple fade-out animation.

<?xml version="1.0" encoding="utf-8"?>
<!--
    -zAdjustment makes sure the activity is on top
    -interpolator defines the rate of change of an animation
    -we use decelerate_interpolator to reduce animation speed from visible (Alpha 1.0) to invisible (Alpha 0.0)
-->
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:toAlpha="0.0"
    android:zAdjustment="top" />

codeofaninja350pxwidth.png – our example logo.

Output screenshots:

Splash screen.

Splash screen.

Main Activity.

Main Activity.

Thanks for reading this Ways to Create a Splash Screen for Android App!

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 sqlite database crud tutorial with example app

Android SQLite Database CRUD Tutorial with Example Application

android-sqlite-database-crud-tutorial-min

This is a step by step android CRUD tutorial where we’ll create an Android application that demonstrates Android’s SQLite database capabilities.

Operations such as create, read, update and delete (CRUD) in Android is an essential skill every aspiring Android developer must have.

In this post, we will cover the following contents:

Read more