Android App Development With AndroidCource: September 2017

Friday 15 September 2017

Android View Pager

What is View Pager ?


ViewPager is the widget that allows the user to swipe left or right to see an entirely new screen.

ViewPager has the ability to dynamically add and remove pages (or tabs) at anytime.

ViewPager are user could then swipe left or right to see other categorized lists. Using the ViewPager requires some knowledge of both Fragments and PageAdapters.

Pager Adapter

Android ViewPager is a layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.

The PagerAdapter providing the adapter to populate pages inside of a ViewPager.

It does not Required Fragment only use on xml layout file to attach in view pager.

It is limited (fixed) number of items (Fragments).

it never removes a fragment instance from FragmentManager.

When you implement a PagerAdapter, you must override the following methods at minimum:

instantiateItem(ViewGroup, int)

destroyItem(ViewGroup, int, Object)

getCount()

isViewFromObject(View, Object)

FragmentStatePagerAdapter


It is Required and implementation Fragments.

A FragmentStatePagerAdapter is more memory savvy.

It completely removes Fragment instances from the FragmentManager once they are out of reach.

The state of the removed Fragments is stored inside the FragmentStatePagerAdapter.

Android Recycler View

Recycler View


Android RecyclerView is more advanced version of ListView with improved performance and other benefits.

Recycler view using Card view.

Recycler view allow different layout manager.

Recycler view Linear Layout,Grid Layout Staggered Grid Layout are easy to Creates.

Recycler view use to ViewHolder store reference of the view.

A ViewHolder class is inner static class in your adapter which holds reference to the views.

The view holder objects are managed by an adapter, which you create by extending the RecyclerView.Adapter abstract class.

Adapter to bind view holders data.It is assigning the view holder position and call adapter onBindViewHolder() method.

Recycler view Adding Animation for adding and removing items.

Use this Dependency in gradle file.


dependencies compile "com.android.support:recyclerview-v7:25.3.1"

Card View

Card View extends FrameLayout. And show item is cards.

Card Vew use attribute is card_view:cardElevation dynamic shadow.

card_view:cardCornerRadius attribute use to set corner radius in the layout.

CardView.setRadius attribute use to set in the code.

card_view:cardBackgroundColor attribute use to set card background.

Use this Dependency in gradle file.


dependencies compile "com.android.support:cardview-v7:25.3.1" 

Android Shared Preference

Shared Preference


Shared Preferences allow you to save and retrieve data in the form of key,value pair.

Shared preferences call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

The first parameter is the key and the second parameter is the MODE.

Preference Access Three API to Choose.

Methods of Shared Preference

getPreferences()

used from within your Activity, to access activity-specific preferences.

getSharedPreferences()

used from within your Activity (or other application Context), to access application-level preferences.

getDefaultSharedPreferences()

used on the PreferenceManager.

What is Mode ?

mode is the operating mode.

Listout Mode to Apply on Preference.

MODE_PRIVATE

This is default mode, where the created file can only be accessed by the calling application.

MODE_WORLD_READABLE

This mode allow other application to read the preferences.

MODE_WORLD_WRITEABLE

This mode allow other application to write the preferences.

MODE_MULTI_PROCESS

This method will check for modification of preferences even if the Shared Preference instance has already been loaded.

MODE_APPEND

This will append the new preferences with the already existing preferences.

MODE_ENABLE_WRITE_AHEAD_LOGGING

Database open flag. When it is set , it would enable write ahead logging by default.

Android External Storage

External Storage


Every Android-compatible device supports a shared "external storage" that you can use to save files.

This can be a removable storage media (such as an SD card) or an internal (non-removable) storage.

storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.

All applications can read and write files placed on the external storage and the user can remove them.

Android Internal Storage

Internal Storage


Store private data on the device memory.

Save files directly on the device's internal storage.

By default, files saved to the internal storage are private to your application and other applications cannot access the user.

Create and write a private file to the internal storage

Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.

Write to the file with write().

Close the stream with close().

Methods of Internal Storage


getFilesDir()

Gets the absolute path to the filesystem directory where your internal files are saved.

getDir()

Creates (or opens an existing) directory within your internal storage space.

deleteFile()

Deletes a file saved on the internal storage.

fileList()

Returns an array of files currently saved by your application.

Android Alert Dialog

Alert Dialog


AlertDialog can be used to display the dialog message with OK and Cancel buttons.

AlertDialog is composed of three regions: title, content area and action buttons.

A dialog is a small window that prompts the user to make a decision or enter additional information.

AlertDialog is the subclass of Dialog class.

AlertDialog need to make an object of AlertDialogBuilder which an inner class of AlertDialog.

Now you have to set the positive (yes) or negative (no) button using the object of the AlertDialogBuilder class.

Methods of AlertDialog


setMessage()

Sets the message to be displayed in the alert dialog

setIcon()

sets the icon in the alert dialog

setCancelable()

Sets the property that the dialog can be cancelled or not

setTitle()

Set the title to be appear in the dialog

show()

Show Display Dialog

Android Popup Menu

Popup Menu


A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu.

It disappears if you click outside the popup

Inherited from android.widget.PopupMenu is the direct subclass of java.lang.Object class.

Android Context Menu

Context Menu


Context menu appears when user press long click on the element.

A context menu is a floating menu.

It provides actions that affect the selected content or context frame.

It doesn't support item shortcuts and icons.

Android Option Menu

Option Menu


Option Menus are the primary menus of android.

It is used for settings,search item,delete items etc.

Inflating on the menu by calling the inflate() method of MenuInflater class.

Event handling on menu item you need to implement override method is onOptionsItemSelected() Activity.

Create Menu inside the res/Menu directory.

Thursday 14 September 2017

Android Services

Introduction in Services


A service is a component which runs in the background without direct interaction with the user.

Service is a no user interface.

Service are used for long running operations. ex. Internet Downloads,check new Data etc..

A service can essentially take two states

1. Started

2. Bound


1.Started

A service is started when an application component, such as an activity, starts it by calling startService().

Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.

For example, it can download or upload a file over the network. When the operation is complete, the service should stop itself.


2. Bound

A service is bound when an application component binds to it by calling bindService().

A bound service runs only as long as another application component is bound to it.

Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC).


Services Lifecycle



Life cycle of services show when the service is created with startService() and the diagram on the right shows the life cycle when the service is created with bindService().


Lifecycle Callback Methods

onStartCommand()

The system invokes this method by calling startService() when another component (such as an activity) requests that the service be started.

When this method executes, the service is started and can run in the background indefinitely.

onBind()

The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC).

In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an IBinder.

onCreate()

The system calls this method when the service is first created using onStartCommand() or onBind().

This call is required to perform one-time set-up.

onUnbind()

This method when all clients have disconnected from a particular interface published by the service.

onRebind()

This method when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent).

onDestroy()

When the service is no longer used and is being destroyed.


Service should implement this to clean up any resources such as threads, registered listeners, receivers, etc.





Android SeekBar

SeekBar


SeekBar is a ProgressBar with a draggable thumb.

SeekBar drag to the thumb on left to right move the progress.

The SeekBar.OnSeekBarChangeListener event handling for seek bar.

Android Time Picker

Time Picker


TimePicker is used to select time of the day.

Select time of the day in 24 hour or AM/PM mode.

Select time by hour and minute.

It can not select time by seconds.

Inherited from android.widget.TimePicker class


Methods of Time Picker

setCurrentHour(Integer currentHour)

Set the current Hours.

setCurrentMinute(Integer currentMinute)

Set the current Minutes.

is24HourView()

This method return true if this is 24 hour is view else false.

setIs24HourView(Boolean is24HourView)

Set 24 hour or AM/PM mode.

setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTimeChangedListener)

This method invoke has been adjusted time by the user.

Android DatePicker

DatePicker


DatePicker is a select date.

Select date on the day,month and year.

Inherited from android.widget.DatePicker this class.

This functionality provides on DatePicker and DatePickerDialog components.


Methods of DatePicker


getDayOfMonth()

This method gets the selected day of month

getMonth()

This method gets the selected month

getYear()

This method gets the selected year

getCalendarView()

This method return show calendar view.

updateDate(int year, int month, int dayOfMonth)

Updates the current date.

Android Spinner

Spinner


Spinner is a Click spinner will display drop-down list with the available values.

Inherited spinner class from “android.widget.Spinner”

It provides a quick way to select one value from a set. By Default spinner show currently selected value.

Spinner is like the ComboBox of AWT or Swing in the Java.

It can be used to display the multiple options to the user in which only one item can be selected by the user.

spinner is associated with AdapterView.it can use one of the adapter class with spinner.


What is ArrayAdapter ?

ArrayAdapter class can handle a list or array of Java objects as input.

Every Java object is mapped to one row.

By default it maps the toString() method of the object to a view in the row layout.

An adapter is used for managing the items in the list.

Android ToggleButton

ToggleButton


A ToggleButton displays checked/unchecked states as a button.

It is basically an on/off button with a light indicator.

ToggleButton Attributes

android:textOn

This is the text for the button when it is checked.

android:textOff

This is the text for the button when it is not checked.

android:text

This is the Text to display.

Android GridView

Grid View


GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

GridView is mainly useful when we want show data in grid layout like displaying images or icons.

This layout can be used to build applications like image viewer, audio or video players in order to show elements in grid view.

Android ListView

List View


ListView is a view group that displays a list of scrollable items


What is Array Adapter ?

This adapter when your data source is an array.

ArrayAdapter creates a view for each array item by calling toString() on each item.

An adapter is used for managing the items in the list .

Android Fragments

What is Fragments ?


A Fragment is a piece of an activity which enable more modular activity design.

You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.

Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets

Because a tablet's screen is much larger than that of a handset, there's more room to combine and interchange UI components

You can add or remove fragments in an activity while the activity is running.

You can combine multiple fragments in a single activity to build a multi-plane UI.

A fragment can be used in multiple activities.

Each fragment has its own life cycle methods that is affected by activity life cycle because fragments are embedded in activity..

Fragments were added to the Android API in Honeycomb version of Android which API version 11.

The FragmentManager class is responsible to make interaction between fragment objects.


Types of Fragments


1. Single frame fragments

Single frame fragments are using for devices like mobiles, here we can show only one fragment as a view.


2. List fragments

special list view is called as list fragment


3. Fragments transaction

Move to one fragment to another fragment using Fragment transaction.


Adding a Fragment to an Activity

There are two ways that a Fragment may be hosted inside an Activity

Declare XML Layout File

declare xml layout file on fragment by using < Fragment /> tag.

Example Declare Fragment on xml file

< fragment class="com.example.Fragment" android:layout_width="match_parent" android:layout_height="match_parent" />


Programmatically

Fragments can also be instantiated dynamically by using the FragmentManager.

Fragment Lifecycle


onAttach(Activity)

The fragment instance is associated with an activity instance.

it is called only once when it is attached with activity.


onCreate(Bundle)

The system calls this method when creating the fragment.

It is used to initialize the fragment.


onCreateView(LayoutInflater, ViewGroup, Bundle)

when it's time for the fragment to draw its user interface for the first time.

To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment's layout.

return null if the fragment does not provide a UI.

in sort creates and returns view hierarchy.


onActivityCreated(Bundle)

The onActivityCreated() is called after the onCreateView() method when the host activity is created.

Activity and fragment instance have been created as well as the view hierarchy of the activity.

In this method you can instantiate objects which require a Context object


onViewStateRestored(Bundle)

provides information to the fragment that all the saved state of fragment view hierarchy has been restored.


onStart()

The onStart() method is called once the fragment is visible.


onResume()

The oResume() method is called once the fragment become active and show user to interactive.


onPause()

The oResume() method is called once the fragment become the user is leaving the fragment.


onResume()

The oResume() method is called once the fragment become the user is leaving the fragment.


onDestroyView()

The onDestroyView() method is called Fragment view will destroy after call this method.


onDestroy()

The onDestroy() method is called The fragment to do final clean up of fragment state.


onDetach()


onDetch() method is called the fragment no longer being associated with its activity.





Android Intent

What is Intent ?


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

It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

There are separate mechanisms for delivering intents to each type of component − activities, services, and broadcast receivers.

startActivity()

The Intent object is passed to this method to launch a new activity or get an existing activity to do something new.

startService()

The Intent object is passed to this method to initiate a service or deliver new instructions to an ongoing service.

sendBroadcast()

The Intent object is passed to this method to deliver the message to all interested broadcast receivers.

Intent Objects

An Intent object is a bundle of information which is used by the component that receives the intent as well as information used by the Android system.

Types of Intents

Implicit Intent

Implicit Intent doesn't specifiy the component.intent provides information of available components provided by the system that is to be invoked.

Example

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


Explicit Intent

Explicit Intent specifies the component.intent provides the external class to be invoked.

Example

            Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
            startActivity(i);


Android Activity

What is Activity ?

An activity represents a single screen with a user interface just like window or frame of Java.The help of activity, you can place all your UI components or widgets in a single screen.


Activity LifeCycle


To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of seven callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(),onRestart() and onDestroy(). The system invokes each of these callbacks as an activity enters a new state.


List out Activity  Lifecycle methods


onCreate()

This is the first callback and called when the activity is first created.

onStart()

This callback is called when the activity becomes visible to the user.

onResume()

This is called when the user starts interacting with the application.

onPause()

This callback is called when activity is not visible to the user.

onStop()

This callback is called when the activity is no longer visible.

onRestart()

This callback is called when the activity restarts after stopping it.

onDestroy()

This callback is called before the activity is destroyed by the system.





Android Software Stack or Android Architecture

List Out Android Software Stack or Android Architecture
Linux Kernel

Linux kernel is responsible for device drivers, power management, memory management, device management and resource access. It is heart of android architecture.

Libraries

Running On the top of linux kernel.Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc.

Android Run Time

Android Runtime are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run android application.Core Libraries libraries provide most of the functionality available in the core Java libraries as well as the Android-specific libraries.The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is intrinsic in the Java language.

Application Framework

The application framework provides the classes used to create Android applications.Android framework includes Android API's such as UI (User Interface), telephony, resources, locations, Content Providers (data) and package managers. It provides a lot of classes and interfaces for android application development.

Applications

On the top of android framework, there are applications.All applications such as home, contact, settings, games, browsers are using android framework that uses android runtime and libraries.


Android History

What is Android ?

Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. It is developed by Google and later the OHA (Open Handset Alliance). Android is mainly using Java Language write the android code.

The code(Version) names of android ranges from A to N currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat, Lollipop Marshmallow and Nought.007, Google announces the development of android OS.

And 2008, HTC launched the first android mobile.

Features Of Android

It is open-source.

Anyone can customize the Android Platform.

There are a lot of mobile applications that can be chosen by the consumer.

It provides many interesting features like weather details, opening screen, live RSS (Really Simple Syndication) feeds etc.

Provides Support in android.


Connectivity

Messaging

Storage

Media support

Web browser

Multi-touch

Multi-tasking

Multi-Language

Video calling

Screen Capture

External Storage

Categories of Android applications


Entertainment

Communication

Tools

Personalization

Productivity

Music and Audio

Media and Video

Social

Travel and Local


Thursday 7 September 2017

Read Phone Contacts Example in Android

MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.bhaumik.readcontectdemo.MainActivity">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

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

        <TextView
            android:id="@+id/text_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:text="Text Name"
            android:layout_marginTop="20dp"
            android:textSize="16dp"
            android:textStyle="bold" />


    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:text="Hello"
        android:layout_marginTop="20dp"
        android:textStyle="bold" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000"
        android:layout_marginTop="10dp"/>
</LinearLayout>
ContactData.java

package com.example.bhaumik.readcontectdemo;

/**
 * Created by Bhaumik on 9/6/2017.
 */

public class ContactData {

    String name,number;

    public String getName() {
        return name;
    }

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

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}
MainActivity.java

package com.example.bhaumik.readcontectdemo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    ListView listView;
    ContactData contactData;
    List<ContactData> list = new ArrayList<>();

    ContactAdapter adapter;

    int counter;

    private static final int REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CODE);

        }else{

            getContacts();

        }

    }

    private void getContacts() {
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,null,null,ContactsContract.CommonDataKinds.Phone.NUMBER);

        if(cursor.getCount()>0){
            counter =0;
            while (cursor.moveToNext()){

                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME ));
                String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                contactData = new ContactData();

                contactData.setName(name);
                contactData.setNumber(phone);

                list.add(contactData);
            }

            adapter = new ContactAdapter(MainActivity.this,R.layout.item_list,list);
            listView.setAdapter(adapter);


        }
        cursor.close();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission is granted
                getContacts();
            } else {
                Toast.makeText(this, "Permission Cancel.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
ContactAdapter.java
package com.example.bhaumik.readcontectdemo;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;

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

/**
 * Created by Bhaumik on 9/6/2017.
 */

public class ContactAdapter extends ArrayAdapter<ContactData>{

    Context context;
    List<ContactData> list = new ArrayList<>();

    public ContactAdapter(@NonNull Context context, @LayoutRes int resource,List<ContactData> list) {
        super(context, resource,list);

        this.context = context;
        this.list = list;

    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Nullable
    @Override
    public ContactData getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        ViewHolder viewHolder;

        if (convertView == null){

            viewHolder = new ViewHolder();

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.item_list,parent,false);
            viewHolder.name = convertView.findViewById(R.id.text_name);
            viewHolder.number = convertView.findViewById(R.id.text_view);
            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }


        viewHolder.name.setText(list.get(position).getName());
        viewHolder.number.setText(list.get(position).getNumber());

        return convertView;
    }

    public class ViewHolder{
        TextView name,number;
    }

}

Letters Alphabets with Listview Example in Android

Add Library
 compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
  
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.bhaumik.listviewwithletters.MainActivity">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
item_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="50dp"
        android:layout_height="50dp"
         />

    <TextView
        android:id="@+id/text_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="70"
        android:gravity="center"
        android:text="Hello"
        android:textStyle="bold" />


</LinearLayout>
MainActivity.java
package com.example.bhaumik.listviewwithletters;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView listView;
    ArrayList<String>list = new ArrayList<>();
    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);

        list.add("Apple");
        list.add("Banana");
        list.add("Cheery");
        list.add("Damson");
        list.add("Elderberry");
        list.add("Feijoa");
        list.add("Grape");
        list.add("Grapefruit");
        list.add("Honeyberry");
        list.add("Jackfruit");
        list.add("Kiwifruit");
        list.add("Lemon");
        list.add("Lime");
        list.add("Mango");
        list.add("Papaya");
        list.add("Pineapple");

        adapter = new ListAdapter(MainActivity.this,R.layout.item_list,list);
        listView.setAdapter(adapter);
    }
}
ListAdapter.java
package com.example.bhaumik.listviewwithletters;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;

import java.util.List;

/**
 * Created by Bhaumik on 9/6/2017.
 */

public class ListAdapter extends ArrayAdapter<String>{

    Context context;
    List<String> list;

    public ListAdapter(@NonNull Context context, @LayoutRes int resource, List<String> list) {
        super(context, resource,list);

        this.context = context;
        this.list = list;

    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Nullable
    @Override
    public String getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        ViewHolder viewHolder;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null){

            convertView = inflater.inflate(R.layout.item_list,parent,false);

            viewHolder = new ViewHolder(convertView);

            convertView.setTag(viewHolder);
        }else{

            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.textView.setText(getItem(position));

        String letters = String.valueOf(getItem(position).charAt(0));

        ColorGenerator colorGenerator = ColorGenerator.MATERIAL;

        int color = colorGenerator.getColor(getItem(position));

        TextDrawable textDrawable = TextDrawable.builder()
                .buildRound(letters,color);

        viewHolder.imageView.setImageDrawable(textDrawable);
        return convertView;
    }

    public class ViewHolder{
        ImageView imageView;
        TextView textView;

        public ViewHolder(View iteView) {
            imageView = iteView.findViewById(R.id.image_view);
            textView = iteView.findViewById(R.id.text_view);
        }
    }
}

Output