how to install kotlin plugin in android studio
how to install or add kotlin plugin in android studio

In this post, you will learn how to install or add kotlin plugin in the Android Studio. If you are using Android Studio 3.0 and above just like me, you don’t need to worry about Kotlin plugin. That’s already set for you.

If you are using android studio 2.3 or below, you need to perform below steps to work with Kotlin.

Let’s launch Android Studio.

how to install kotlin plugin in android studio

If you are already opened a project, select File-> close project to land welcome page of Android studio.

Click on configure button and select plugins option.

Click Install JetBrains plugin button

android studio install kotlin

1. Search “kotlin” without quotes or you can scroll down the list and find Kotlin.
2. Click on Kotlin plugin item
3. On the right section of the window, click on the Install button.

android studio install kotlin
Download starts…
android studio install kotlin
After a short time, when download completes. Install button becomes “Restart Android Studio“. Click on that.
android studio install kotlin
Next dialog box appears. Click Restart to activate changes in plugins.

That’s all.
Thanks for scrolling… Please share and your valuable comments also needed for our improvement.

how to use toast in android with example -

Have you ever seen “touch again to exit” or any other white text in a black capsule shape as pop up in Android???

Those popup messages are toast. In this post, you will learn how to use toast in android with a simple example.

Okay… what is toast ???

Toast is the subclass of java.lang.Object class, and it helps developers to make notification message that appears at the bottom of the screen by default. The temporary message pops up and fades away after a short time. Just like hot bread pop up from a toaster. While showing toast you can still access your activity.

Okay…Let’s make a toast in android

How to make toast in Android?

how to make toast in android -

You can make toast in 2 simple steps.

    1. Call static method  makeText() of Toast class and give
      •  Context
      • CharSequence or String resource id
      • Int duration : LENGTH_LONG or LENGTH_SHORT
    2. Call show() method

Make a toast in one statement.

Don’t forget to add show() method, because it happens sometimes for me and think why the code doesn’t work after a long stare at the bottom of the screen.

You can make toast in background services, if your application not in the foreground while toast showing up,  toast may confuse the users. So use appropriate text with the toast to assist users to digest easily.

What happens if there is no text ??

what happens if the code like below??

then the output will be as shown text in toast android

When you call makeText with your parameter value. Internally, it inflates $YOUR_SDK$/platforms/android-22/data/res/layout/transient_notification.xml and set your content to textview which have id message.

android-22 is API level, It may change based on your SDK.

How to change the position of Toast?

Just told you earlier, Toast pop up at bottom of the screen, center-horizontally. Toast class provides

setGravity(int gravity_constant,int xOffsetValue, int yOffsetValue)

method to position your toast where you want.

  1. int gravity_constant: Android provides lots of Gravity constant values. Just like CENTER, TOP, RIGHT, BOTTOM and so on.
  2. int xOffsetValue : If you want to change the position of your toast to the right, increase this value.
  3. int yOffsetValue : If you want to change the position of your toast to downward, increase this value.

Below code will place your toast to center of the screen.

you can use more gravity constants using the vertical line (|) symbol.

Below code places your toast to CENTER-RIGHT end.

More about Toast class

static constants

LENGTH_LONG: It shows view or toast for almost 3.5 seconds.

LENGTH_SHORT: It shows view or toast for almost 2 seconds.

Public constructor

Toast(Context context)

It creates a Toast object.

Public methods

i) public void cancel()

It hides the toast if it is already showing or if it isn’t visible yet.

ii) public int getDuration()

It returns the duration of view or toast. (LENGTH_LONG or LENGTH_SHORT)

iii) public void getGravity()

It returns location if that is already set.

iv) public float getHorizontalMargin()

it returns the horizontal margin in float.

v) public float getVerticalMargin()

it returns the vertical margin in float.

vi) public View getView()

It returns the view. You can access view items using this method.

vii) public int getXOffset() && public int getYOffset()

It returns X offset and Y offset in Pixels.

viii) public void setDuration(int duration)

Use this method to set duration of your toast or view.

ix) public void setMargin(float horizontal_margin, float vertical_margin)

Use this method to set margins of your view or toast. actually here margin means how much space needed between toast and side of the screen.

x) public void setText(int Resource_id or CharSequence string)

There are two variations of setText(…) method. One receives parameter as charSequence and other receives as string resource id. You can update the text in the toast that previously you create with makeText() method.

xi) public void setView(View view)

It sets the view for toast. It’s helpful while creating a custom view.

xii) public void show()

It shows the toast or view.

Let’s Create a project…

In this project, we will make a button inside linearlayout. When the button is tapped, a toast will appear at the center of the screen with application name in it.

File->New->New Project

Application name: Toast Ex

company domain:

click Next and select your minimum SDK and empty activity template.

Activity name: MainActivity

Layout name: activity_main.xml

click Finish.

open activity_main.xml, and paste below code.
Linearlayout gravity attribute place button at the top position, center-horizontally. android:onClick attribute calls showToast() method in MainActivity. Then the toast appears.

open and paste below code

Here, makeText() method returns a toast object and Using toast instance setGravity() method position toast at the center of the screen and show() method helps to display the toast.

Run now

android toast example screenshot- how to use toast in android -

Don’t worry if your actionbar color is blue. You can change it through by copy-pasting my colors.xml given in full code.

For more information
Visit Toast documentation

Download Toast Example

Sharing is caring…..

In Android app development, support libraries have an important role. Without them, It might difficult to provide a consistent look and feel in all devices.

If you are a beginner and experimenting with online tutorials, there may be a chance to edit the gradle file directly for adding the library as a dependency, sometimes wait for a download too.

Before doing that you can perform the following procedures to find and add an available version of the same support library. You can use this way to add appcompat, design, cardview, recyclerview and so on.

Now we will add design support library to our project. We assume that you opened Android Studio and  your project.

Okay… Let’s go.

  1. File->Project Structure you can use “Ctrl + Alt + Shift + S ” key combinations.file project structure - how to add support library in android studio
  2.  click  the app module - how to add support library in android studio
  3. Click the Dependencies tab, you will see the already added libraries below. click the + Button shown in the  Right side of the window.dependency tab and + button - how to add support library in android studio -
  4.  Choose library dependency from available options.library dependency - how to add support library in android studio -
  5. Choose library dependency dialog will be visible now. You can search here or choose the desired library that you want from the list. After your selection, just click OK.choose library dependency dialog - how to add support library in android studio -
  6. The selected library will be added as a dependency in your dependencies tab list and click OK.
    library added - how to add support library in android studio -
  7. Just look at the build.gradle(Module: app)  file dependency section, Android Studio will have added your selected - how to add support library in android studio -androidride.comPlease share it and your valuable comments will help us to improve.


In this post, you will learn how to perform an action using Button and onClick attribute in XML. It is simple and easy to understand. Before creating the project, Let’s know more about android:onClick attribute in Android.

How android:onClick XML attribute works here with Button?

android button onclick - How it works

For detecting tap or button click event in android we can use android:onClick attribute. When users tap the views which hold android:onClick ,  android looks for the method in activity. If the exact method found, that will start execution. So, provide a valid method name that lives in hosted activity as the XML attribute value. Not only Button It works for ImageButton, CheckBox, and RadioButton too.

we can specify onClick attribute just like given below:


For a better working of onClick attribute, you must take care these:

  1. The method name must be the same in value of onClick attribute and in Activity.
  2. The method has to accept a View parameter. The view here means which holds onClick xml attribute or which view was clicked. here, that is button
  3. it needs to return a void value.
  4. the method must be defined as public.

If you don’t obey above ones, most of the time you will end with an exception.

Let’s create a project, In this project, we will add a Button and TextView, When the user taps the Button it calls a method in the activity depends on android:onClick value and set text in TextView.

We assume that you opened Android Studio.

Step 1

File->New ->New Project

Application Name: OnClick XML Ex

Company Domain:

click Next

Step 2

Select the form factors and minimum SDK

tick the phone and tablet checkbox and choose API 15: Android 4.0.3(IceCream Sandwich) and click Next.

Step 3

Select Empty Activity template

For this project, we just need an empty activity template. So just select the empty activity template and click Next.

Step 4

Create a new empty activity and layout

Next screen prompt for making an activity class file and its layout.

Activity Name: MainActivity

Tick the generate the layout checkbox if it’s not checked.

Layout Name: activity_main

Tick Backward Compatibility checkbox and Click finish.

Step 5

open activity_main.xml and paste the below code

You can drag LinearLayout, Button, and TextView wherever you want and give id, onClick attribute as you want or you can simply paste the below code. The layout just contains the Button and TextView inside LinearLayout.

Now you can see android:onClick value (myMethod) is underlined with red color and gives you an error message that “Corresponding method handler ‘public void myMethod(android.view.View) not found.

This is because we didn’t define the method in our MainActivity class.

Step 6
Define myMethod and set text

Obeying all rules specified earlier, create myMethod() and initialize and set the text to textview.

Just run your app.

screenshot button onclick xml example - Simple guide Button onclick xml example in android -

For more information
Button google docs

Download Button OnClick XML Example
Please share this post and your valuable comments will help us to improve.

In this post, you will learn how to create another activity in Android Studio. This method will add activity details in AndroiManifest.xml. Hence, there is no chance for ActivityNotFoundException.

Let’s create a new activity…

Step 1

Right click on project package (here com.androidride.createactivity3) in App-> Java. and select New -> Activity -> Empty Activity/Blank activity.

First of all, make sure you are in Android view in the project explorer. Some views don’t have new activity option. If you are in other views, Just click on the downward arrow and choose Android from the given options.

It’s not a problem if you don’t see Empty Activity option. In older versions of Android studio, you might find Blank activity option. Both of them are the same just a name difference. Don’t use Basic activity now because that’s the advanced version of Empty Activity/Blank activity and contains Floating action button.
new empty activity - how to create another activity in android studio

Step 2

Enter the Activity name and click Finish.

Enter your activity name, at the same time layout layout name automatically fills up for you if Generate layout file checkbox is checked.
Then Backwards compatibility(AppCompat) option will give the app a certain look in almost all devices, at the same time your activity will extend AppCompatActivity class. For a beginner like you, you can leave the option as empty that cause your activity to extend Activity class and Click Finish.

configure new-activity- how to create another activity in android studio
Your activity files are created. congrats…

new file structure - how to create another activity in android studio

You can also create another activity in the Android Studio using the File menu option.

File -> New -> Activity -> Empty Activity & step 2.

But the First method will be easy and quick when you are coding…

asynctask in android with example -

In this post you will learn about AsyncTask in Android. At last you can download the example too.


Have you ever feel your app or downloaded one

  • Lazy to perform
  • Not responding to user inputs
  • No smooth UI update

And at last, leads to Application not responding (ANR) dialog ???

Why is this happening?

As a matter of fact, Your application performs a too much intensive task on UI thread, at the same time it takes time to complete. For the sake of user convenience, Android system will show you ANR dialog and stop your app forcefully.

In more detail, When the app gets started execution, Main thread or UI thread gets created. By default, all lifecycle methods like onCreate(,onStart(), and onClick, UI update works are serially done by UI thread. But When app developer put complex operations like

    • Network operations.
    • Disk I/O tasks.
    • Database Queries.
    • Other CPU intensive actions.

The app needs more time to perform. So at that time UI thread can’t update or repaint user interface. App freezes, operations exceeds the definite time fixed by the Android system. finally, the system decides to kill the application to make the device available to the user for other acts.

For making a neat and smart app, you should avoid all complex scenarios performing on UI thread.

Then what to do??

Where do we put our code to gets executed ??

You can use threads.

While performing these operations, You should notify the user through UI that something is happening behind. Otherwise, the user doesn’t know what is happening in your app. But you can’t perform any UI updations from your threads, that job is done by one and only Main Thread or UI thread. Then how could we use main thread to notify the user?

Hello, is there any solution?

Yes, For beginners, use AsyncTask.

What ??


Full name, please??


nice name.. Carry on.

Asynctask is just like a side road - The Beginner's Guide : AsyncTask in Android tutorial with Example

AsyncTask is just like a side road, while large-slowly moving truck makes traffic problem on the main road, Asynctask keeps those away to make a better path for other traffic.

For beginners, It’s the first and one of the best option for performing difficult work.

Okay… find out more about AsyncTask.

What is AsyncTask in android?

AsyncTask name came from the asynchronous task. It is an abstract class and you can find it on Android SDK. It helps Android app developers to execute operations like

  • Downloading and uploading files like JSON, XML, images, and small size other files.
    You can’t perform network operations on main thread since Honeycomb – API level 11. The system will throw android.os.NetworkOnMainThreadException. However, you must use AsyncTask or threads to perform network tasks.
  • Storing and reading data from large text files.
  • All Database CRUD(create,read,update,delete) operations.
  • Other CPU intensive operations.

In background or worker thread. Same time helps to update UI on UI thread. Asynctask makes use of UI thread in a better manner.

It eases the tension of developers from

  • Thread creation and termination.
  • UI thread synchronization and management.


How to use AsyncTask in your project

how to use asynctask in your application or project - androidride
In this part, I will explain in more detail.

First of all, If you

  • do not know how much time needed for your task or task takes a long time
  • Want to perform an infinite loop work

AsyncTask is not a better option for you. AsyncTask mostly used for short operations(a few seconds at the most)

To make AsyncTask do work, we want to do 3 most important things.

1)Create a subclass of AsyncTask
2)Override doInBackground() and other methods.
3) Make an instance of AsyncTask subclass  & call execute().

1)Create a subclass of AsyncTask

For performing different types of data operations, AsyncTask uses generics. So while making a subclass of AsyncTask, you must specify 3 generic data types.

Params, Progress, Result

1)Params: data used to start background thread execution.

For example, AsyncTask downloading an image file using URL, then specify URL as params.

2) Progress: data that used to notify progress of the task.

While downloading an image, You want to show the user that how much percentage of the image has been downloaded. So you can use Integer as Progress.

3)Result : data that return from doInBackground() after execution.

For the same image downloading example, you can use Bitmap if doInBackground() code returns an image.


Class Subclass_Name extends Asynctask

In real,

What if you do not want to

  • Pass parameters to doInBackground()?
  • Show progress to the user?
  • Return any result?

You can use Void data type just like other.

Do not use primitive data types as parameters.

This is wrong.

2) Override doInBackground() and other methods


Optional. It calls before task executes on the background thread and you can use it to set up a task. It runs on UI thread, so you can access UI elements here. In most cases, the app will perform animation or set visible Progressbar or progressdialog.

doInbackground(Params… params)

Most important method in AsyncTask, After the successful completion of onPreExecute() it leads to doInbackground(). It does all intensive task in the background thread. It receives parameters as varargs. Varargs means a variable number of arguments(like an array of elements), it can receive a number of parameters. You can access each element using index just like the array.

While performing a repetitive task, you can publish it’s progress through onProgressUpdate using publishProgress(). Which data type returns from doInbackground, that type must be the parameter of onPostExecute().

If you use AsyncTask only for implementing doInBackground(), Use java threads.


This method is used to connect and pass data from doInbackground() to onProgressUpdate(). Just like a bridge.

onProgressUpdate(Progress… progress)

Optional. It also uses varargs as parameters. It runs on UI thread, so you can use this method to notify task’s progress.

For an example. If your app downloading lots of images. There may be a chance to user gets bored. So you can publish each photo to the user through onProgressUpdate(). That must be a great relief to the user.

The progress won’t directly published on Main Thread. It uses handler internally bound to Main thread looper for execution. If there is lots of work in Main Thread, progress will not update smoothly.

onPostExecute(Result result)

This is also optional and runs on Main thread. It’s the most used second method in Asynctask. After successful completion of doInbackground, onpostExecute() starts with result from doInBackground. In some cases, this method uses to stop animation or hide progress bar that you started in onPreExecute().

onCancelled(Result result)

Optional and runs on Main thread. It invokes only when cancel method is called with the instance of AsyncTask subclass. It will not invoke if doInBackground completes. After its completion, it will assign control to onCancelled() with no parameters. Override onCancelled() when nothing returns from doInBackground(). Use this to avoid checking data is null or not.

You can make different UI appearance for successful and fail completion by using onPostExecute() and onCancelled().

Note: Do not call these methods manually, you can. But don’t.

These methods are callbacks exept publishProgress, they will invoke automatically by the system at appropriate time.

3)Make an instance of AsyncTask subclass  & call execute()

Android provides 2 methods to start AsyncTask.

1) execute (Params… params)
2) executeOnExecutor (Executor exec, Params… params),  added in API level 11.

Call these methods using an instance of the asynctask subclass. doInBackground get their parameter data from these methods.

When asynctask added at first, execute method preferred serial execution. Later, means API level 4 android engineers change their decision to execute in parallel and it continues to level 12. With the introduction of executeOnExecutor() at API level 11, they give concurrency control to the developer. The app developer can decide that how to execute our task in serial or parallel.

Two Executor parameter determines concurrency:

1.SERIAL_EXECUTOR: This executor parameter uses for performing a serial execution, they start each task after completing one by one. They promise that each task will complete in the order they were started or added. Just like a Queue.

2.THREAD_POOL_EXECUTOR: You can pass this executor object to perform a parallel execution, they do not give you any guarantee to complete the task in the order they were started. Asynctask will start as soon as possible when they get a thread from the thread pool

Due to issues in parallel execution, at API level 13, execute() set back to serial execution.

Both these codes have same meaning from API level 13

Note: execute() must be invoked on UI thread and task instance must be created on UI thread

Just like threads, asynctask execute only once. If you try to execute more than once with the same reference to asynctask subclass you will end with an exception with message Cannot execute task: the task has already been executed (a task can be executed only once)

If you try to execute the same task with the same reference to asynctask subclass while it running another exception will be thrown with the message “ Cannot execute task: the task is already running.

So don’t do this.

If you want to execute the same asynctask more than once, just create a new instance and call execute.

How to cancel AsyncTask

What if the user selected a wrong option and want to cancel a running task?

AsyncTask provides a better cancellation strategy, to terminate currently running task.

cancel(boolean mayInterruptIfitRunning)

myTask.cancel(false)- It makes isCancelled returns true. Helps to cancel the task.

myTask.cancel(true) – It also makes isCancelled() returns true, interrupt the background thread and relieves resources .

It is considered as an arrogant way, If there is any thread.sleep() method performing in background thread, cancel(true) will interrupt background thread at that time. But cancel(false) will wait for it and cancel task when that method completes.

If you invoke cancel() and doInBackground() hasn’t begun execute yet. onCancelled() will invoke.

After invoking cancel(…) you should check value returned by isCancelled() on doInbackground() periodically. just like shown below.

AsyncTask’s Status

asynctask status - Asynctask in adnroid with example -

Asynctask tells their current state by giving below status.

1. PENDING: In this state, AsyncTask is not started, execute or executeOnExecutor() is not invoked. But you have created an asynctask instance.

2. RUNNING: Asynctask started their job, it will remain in this state from onPreExecute to onPostExecute or onCancelled.

3. FINISHED : This state will set when onPostExecute() or onCancelled() is completed.

you can check these statuses by calling getStatus() method using asynctask instance.

Simple AsyncTask Example

Let’s make an application and familiar with Asynctask.

Step 1

Create a new project

In Android Studio, File->New Project

Application Name: AsyncTaskEx

Company Domain:

click Next

Step 2

Select the form factors and minimum SDK

tick the phone and tablet checkbox and choose API 15: Android 4.0.3(IceCream Sandwich) and click Next


Step 3

Select Empty Activity template

For this project, we just need an empty activity template. So just select the empty activity template and click Next.

Step 4

Create a new empty activity and layout

Next screen prompt for making an activity class file and its layout.

Activity Name: MainActivity

Tick the generate the layout checkbox if it’s not checked. Click finish.

Step 5

open activity_main.xml and put the code shown below.

The layout code will add a button and textview, button executes AsyncTask.

Step 6

open and put the code shown below

When you click on button, it will trigger asynctask and textview will update in each second.

Run Now…


Download AsyncTask Example –

For more about AsyncTask

Please share this post & your precious comments will help us to improve.

Are you tired of waiting for gradle to be finished?

Don’t worry, there is a way to reduce android build time and make APK.

Yes, we can.

gradlew.bat file helps us to build our APK (windows). In Mac and Linux, it available in the form of a shell. You can find the file from the root of each project that you created with Android studio.

gradlew file in root project folder of Android studio -Efficient way to reduce android build time

Let’s build our apk…

1) Open the command prompt and navigate to the root folder of your project.

Make sure that you enabled USB debugging on your device and still connected.

2) Type

‘gradlew installdebug’

(without quotes) in command prompt and press enter key.

This command will start building process with use of the gradlew.bat file. If there are no errors, and the APK will be moved to your device and install on it.

Just tap on the app icon manually to launch.

Want to know more about build apps through command line

Please Share this article…..

Do you want to know how setContentView() work in Android?

Let’s start…

Actually setContentView() is a method part of class. It helps to set our content or render our layout on the screen.

What is layout in Android?
The Beginner’s Guide : AsyncTask in Android tutorial with Example

Based on the value given by the user, views will be inflated and rendered after the measurement of the screen, root view, and its child views. Well, here is everything you need to know about setContentView() method.

SetContentView() method is 3 types.

 1) setContentView(int resourceId)

2)setContentView(View view)

3)setContentView(View view, android.view.ViewGroup.layoutparams params)

These all methods available from API level 1. Let’s talk more about these types.

setcontentview in android studio

setContentView(int resourceId)

This method uses layout constant from automatically generated class. class holds many static constant values in nested classes. So that you can access directly by specifying R class and nested class.

Nested Layout class contains layout resource constants to ease the availability of actual files in the resource directory.

At runtime, System will select the appropriate layout based on orientation and other factors like language and region. But default it will select the layout in res/layout directory.

Here, R.layout.activity_main is an integer value contained inside of layout class in file. Using this integer value Android system will look in res/layout directory. That’s how android finds the correct layout.

If you are using XML layout do not try to initialize views before calling setContentView(R.layout.layout_name), because without inflating the layouts, there are no actual views in memory. It will lead to NullpointerException.

setContentView(android.view.View view) in Android

Set any view as your activity’s content. View’s height and width set to MATCH_PARENT as default.

You probably need to add an import android.widget.TextView; statement.

setContentView(View view, ViewGroup.Layoutparams)

Extension of setContentView(View view) method. Here you can specify view’s parameters.

You can add child views to Linearlayout using addView() method.

  • You can call many times setContentView() method, but it works only at the last call.
  • You can use setContentView() outside of the onCreate() method.
  • ListActivity does not use setContentView() Because it already contains a listview and use setListAdapter() to populate.
  • In fragments, LayoutInflater does layout rendering work with inflate() method. Just equivalent to setContentView().
  • Sometimes, you need to display a layout from many layouts based on any condition. Like showing login or signup page. So there is no need to create two activities. Just use if statement or other depends on your needs and do just like below.


That’s all for now. Is there any suggestions, please comment below.

If you are new to android development world, you may have doubts about the word “layout”.

So let’s start here,

what is layout in android -

In Android, layout describes the appearance of the app. Layouts are just resourced files. The instructions or content in layout decides to position your widget and make your user interface.

The layout contains view, viewgroup objects and <merge> tag. Just like HTML, It must have a root element. It can contain more GUI widgets like Button, TextView etc. Nested elements are also supported.

An app can have more than one screens based on developer needs. So you can have many layouts as you want.

Layout resource names must contain only lowercase a-z, 0-9, or underscore otherwise, you might end with an error.

How to create layout in android?

  • Using XML

You can use XML straightforward vocabulary to specify your UI. For beginners, you can check it out drag and drop feature. It helps us to drag a view which you want and drop it wherever you want in layout design. The XML code will automatically complete by android studio.

For localization (translating strings into different languages), XML layout would be a better idea.

Note: You must put xmlns:android attribute with android namespace inside root element.

For an example: assume LinearLayout as your root element.

  • Programmatically at runtime

It’s not generally recommended. There may be occasions to make your layout at runtime. But it mixes up UI code and code that controlling app behavior. So it may become difficult to tweak and refine user interface.

Where is layout files located at?

layout subdirectory in android studio

Android studio automatically creates a directory to hold your layout files – layout subdirectory.

In your project structure

app->res->layout .

all resource files stored in res (resources folder).

How to create a layout file in android studio?

Right Click on your default layout subdirectory

New -> Layout resource file -> Enter layout Name and click OK.

Also give details of the root element, source set, Directory name and other available qualifiers.

How to rename layout file in android studio?

Right click on your layout file which want to rename

Refactor -> Rename -> give new file name -> Refactor. You can use shift + F6 key also.



easiest way to make listview in android
pin me..please 😉

Those messages in the listview are sent by my crush to me.

Yes, that was the best dream I ever had ;-).

I’m just kidding…

Let’s back to the topic,

When beginners make an app for showing a collection of data, Most of them prefer ListView. It is easy to work with listview when comparing its successor RecyclerView. Although ListView becomes old now, uses of ListView still goes on.

Beginners use it well with adapter strategy. But Android API provides an easy way to build a listview.

In this tutorial you will learn to construct listview easily and less code.

The android:entries XML attribute helps us achieve our target.

      • Easy to populate ListView, Spinner, Gallery and ListPreference.
      • Only static, unchanging string data allowed. So you can’t use with data from internet, database,
        shared preferences etc.

How android:entries works ??
pin me …. too

As shown in the picture, android:entries attribute needs an array resource name, not the file name which contains array resource. You can define array resource in strings.xml. Not only listview, Spinner, ListPreference, and gallery also use android:entries attribute. But gallery deprecated in API level 16. As a successor of ListView, RecyclerView doesn’t hold entries attribute.

When the user runs the app, Listview constructor takes the array resource referred in the entries attribute. Then the constructor makes an adapter itself with the simple_list_item_1 layout in SDK. Then assign it to the listview.

Actually, we just point our data to the listview, listview does the all other work.

This is the way how it works.



Step 1

Create a new project

In Android Studio, create a new project File -> New -> Project

Application Name: Simple ListView Ex
Company Domain:

Android convention to use the reverse of the domain name. that’s never a problem for you.
click Next

Step 2

Choose your minimum SDK

It is necessary to choose the minimum SDK that you want. tick the phone and tablet checkbox for making the app for only phone and tablet.

click next

Step 3

Select empty activity template

For this project, we just need an empty activity. So just select the empty activity template and click next.

Step 4

Create a new empty activity and layout

Next screen prompt for making an activity class file and its layout.

Activity Name : MainActivity

Tick the generate the layout checkbox if it’s not checked. Click finish. Now, you will see the MainActivity class

Step 5

Change toolbar and status bar color

You can skip this step if you don’t want to alter the default style. Open res/values/colors.xml and paste the code below for to make a red colored toolbar.

Step 6

Make a string array to hold the contents of the listview.

Open res/values/Strings.xml, and paste the below code between .


Use escape sequence \’ to get the apostrophe in last string.

Step 6

Add android: entries attribute and its value in listview XML definition.

open res/layout/activity_main.xml, delete the existing code and paste the code below.


If you wish to add other widgets to your layout, then you can add viewgroups like RelativeLayout, LinearLayout and other. Then just replace the XML namespace ( xmlns:android=””) from listview to the root element.

Run the app. You will get the output like below.

listview screenshot example - easiest way to make listview in android

How does ListView know did user click on list item ??

Based on tapping sound.

No, Here comes Listener. Listener waits for the events. Such as tapping, touching events.

Here we use OnItemClickListener nested class. Its onItemClick(…) method will trigger when an item in the listview clicked. So place the code that wants to run when click event happens.

Step 7

Create and Instantiate listview variable

In onCreate() method, create listview variable and instantiate using findViewById(int id) method. In this case, id is listview, we must use the same id in XML description. Type cast the returned View object to the ListView.

Step 8

Add listener to listview for listening click events

Add OnItemClickListener and Implement OnItemClick(…) method. Use listview’s setOnItemClickListener() method to register the listener.

Step 9

Display the content in the clicked item.

In onItemClick(…) method, Implement code to reveal the content in listview row. First, Use adapterview’s getItemAtPosition(int position) method to retrieve the data from listview item row. getItemAtPosition() returns data as object in the given position.

Convert it to string using toString() method;

Show the retrieved message using Toast.makeText(context,CharSequence text,int duration) method.

how onItemClick method works with listview in android - Easiest way to make listview in android
pin me… too…

Run it now…

Let’s wrap it up, You can use this attribute if you want a static listview otherwise we would prefer adapter.
Download SimpleListViewEx

For more reference

Spinner, Gallery, and ListPreference

If you like this article, please share.

Thank you for scrolling…