Android Google Maps v2 Tutorial With Markers

In this tutorial, I will show you how to implement google maps in your application.

To use Google Maps in your application we need GoogleMapsApi_Key

you can get this key from google developers console  from here.

we use this API key in AndroidManifest.xml file

Carefully add all permissions in AndroidManifest.xml

For Eclipse ADT users add download google play services library (you can install from SDK Manager) and add them to your project

For Android Studio users add  dependency in your Gradle file

compile 'com.google.android.gms:play-services:8.4.0'

MainActivity.java

package com.androidruler.mymap;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.List;
import java.util.Locale;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {




    TextView addre,location;
    Button getLocation;
    LocationTracker tracker;
    String getadd;
    double latitude=0.0d,longitude=0.0d;
    private GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mmymap);
        mapFragment.getMapAsync(this);
        addre=(TextView)findViewById(R.id.address);
        location=(TextView)findViewById(R.id.location);
        getLocation=(Button)findViewById(R.id.getlocation);
        getLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //create LocationTracker Object
                tracker = new LocationTracker(MainActivity.this);

                // check if location is available
                if (tracker.isLocationEnabled) {
                    latitude = tracker.getLatitude();
                    longitude = tracker.getLongitude();

                    location.setText("Your Location is Latitude= " + latitude + " Longitude= " + longitude);
                    getadd = getCompleteAddressString(latitude, longitude);
                    addre.setText(getadd);
                    drawMarker(latitude, longitude);
                } else {
                    // show dialog box to user to enable location
                    tracker.askToOnLocation();
                }
            }
        });


    }

    @Override
    public void onMapReady(GoogleMap Map) {
        mMap=Map;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setAllGesturesEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(true);

    }

    public void drawMarker(double lat,double lon)
    {
        if (mMap != null) {

            MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lon)).title(" Maps Tutorial").snippet("Android Ruler");

            marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

// Moving Camera to a Location with animation
            CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build();

            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            mMap.addMarker(marker);

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder
                    .getFromLocation(LATITUDE, LONGITUDE, 1);
            if (addresses != null) {
                android.location.Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress
                            .append(returnedAddress.getAddressLine(i)).append(
                            "\n");
                }
                strAdd = strReturnedAddress.toString();
                Log.w(" location address", ""+ strReturnedAddress.toString());
            } else {
                Log.w(" location address", "No Address returned!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.w(" location address", "Cannot get Address!");
        }
        return strAdd;
    }
}

 

LocationTracker.java

 

package com.androidruler.mymap;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
 * Created by androidruler on 24/02/16.
 */
public class LocationTracker extends Service implements LocationListener {

     //declaring Context variable
    private final Context con;

    //flag for gps
    boolean isGPSOn=false;

    //flag for network location
    boolean isNetWorkEnabled=false;

    //flag to getlocation
    boolean isLocationEnabled=false;

    //minimum distance to request for location update
    private static final long MIN_DISTANCE_TO_REQUEST_LOCATION=1; // in meters

    // minimum time to request location updates
    private static final long MIN_TIME_FOR_UPDATES=1000*1; // 1 sec

    //location
    Location location;
    //latitude and longitude
    double latitude,longitude;

    //Declaring a LocationManager
    LocationManager locationManager;

    public LocationTracker(Context context)
    {
        this.con=context;
        checkIfLocationAvailable();
    }

    public Location checkIfLocationAvailable()
    {
        try
        {
            locationManager=(LocationManager)con.getSystemService(LOCATION_SERVICE);
            //check for gps availability
            isGPSOn=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            //check for network availablity
            isNetWorkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if(!isGPSOn && !isNetWorkEnabled)
            {
                isLocationEnabled=false;
                // no location provider is available show toast to user
                Toast.makeText(con,"No Location Provider is Available",Toast.LENGTH_SHORT).show();
            }
            else {
                isLocationEnabled=true;

                // if network location is available request location update
                if(isNetWorkEnabled)
                {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this);
                   if(locationManager!=null)
                   {
                       location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                       if(location!=null)
                       {
                           latitude=location.getLatitude();
                           longitude=location.getLongitude();

                       }
                   }
                }

                if(isGPSOn)
                {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this);

                    if(locationManager!=null)
                    {
                        location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if(location!=null)
                        {
                            latitude=location.getLatitude();
                            longitude=location.getLongitude();
                        }
                    }
                }
            }

        }catch (Exception e)
        {

        }

        return location;
    }

    // call this to stop using location
    public void stopUsingLocation()
    {
        if(locationManager!=null)
        {
            locationManager.removeUpdates(LocationTracker.this);
        }
    }
       // call this to getLatitude
    public double getLatitude()
    {
        if(location!=null)
        {
            latitude=location.getLatitude();
        }
        return latitude;
    }
    //call this to getLongitude
    public double getLongitude()
    {
        if(location!=null)
        {
            longitude=location.getLongitude();
        }
        return longitude;
    }

    public boolean isLocationEnabled() {
        return this.isLocationEnabled;
    }

    //call to open settings and ask to enable Location
    public void askToOnLocation()
    {
        AlertDialog.Builder dialog=new AlertDialog.Builder(con);

        //set title
        dialog.setTitle("Settings");
        //set Message
        dialog.setMessage("Location is not Enabled.Do you want to go to settings to enable it?");
        // on pressing this will be called
        dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                con.startActivity(intent);
            }
        });

        //on Pressing cancel
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // show Dialog box
        dialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}



//layout for MainActivity

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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:id="@+id/mmymap"
        android:layout_alignParentTop="true"
        android:name="com.google.android.gms.maps.SupportMapFragment" />
<Button
    android:id="@+id/getlocation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="getLocation"
    android:layout_below="@+id/mmymap"
    />

    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/getlocation"/>
    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/location"/>

</RelativeLayout>



AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidruler.mymap" >

    <permission
        android:name="com.androidruler.mymap.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.androidruler.mymap.permission.MAPS_RECEIVE" />
    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

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

        <!-- API key for the Android Maps API v2. The value is defined as a string resource. -->
        <meta-data android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyB46A0jQLS9lm1x-fO07tD-EPHzoxCvMkg"/>
    </application>

</manifest>

Android GPS Location Manager Tutorial

if you are making any location-based application you can follow this tutorial to get Location automatically from LocationTracker.java class.

In this tutorial,  I will show you how to get current Location and get an address from latitude and longitude.In this we have

  • MainActivity as Activity to get Location on performing Click
  • LocationTracker class to get Location

MainActivity.java

 

package com.androidruler.mymap;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;

import java.util.List;
import java.util.Locale;

public class MainActivity extends Activity {


   TextView address,location;
    Button getLocation;
    LocationTracker tracker;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        address=(TextView)findViewById(R.id.address);
        location=(TextView)findViewById(R.id.location);
        getLocation=(Button)findViewById(R.id.getlocation);
        getLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //create LocationTracker Object
                tracker=new LocationTracker(MainActivity.this);

                // check if location is available
                if(tracker.isLocationEnabled)
                {
                    double latitude=tracker.getLatitude();
                    double longitude=tracker.getLongitude();

                    location.setText("Your Location is Latitude= " + latitude + " Longitude= " + longitude);
                  String addres= getCompleteAddressString(latitude,longitude);
                  address.setText(addres);
                }
                else
                {
                    // show dialog box to user to enable location
                    tracker.askToOnLocation();
                }
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder
                    .getFromLocation(LATITUDE, LONGITUDE, 1);
            if (addresses != null) {
                android.location.Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress
                            .append(returnedAddress.getAddressLine(i)).append(
                            "\n");
                }
                strAdd = strReturnedAddress.toString();
                Log.w(" location address", ""+ strReturnedAddress.toString());
            } else {
                Log.w(" location address", "No Address returned!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.w(" location address", "Cannot get Address!");
        }
        return strAdd;
    }
}

//location tracker to get current location

LocationTracker

package com.androidruler.mymap;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
 * Created by androidruler on 24/02/16.
 */
public class LocationTracker extends Service implements LocationListener {

     //declaring Context variable
    private final Context con;

    //flag for gps
    boolean isGPSOn=false;

    //flag for network location
    boolean isNetWorkEnabled=false;

    //flag to getlocation
    boolean isLocationEnabled=false;

    //minimum distance to request for location update
    private static final long MIN_DISTANCE_TO_REQUEST_LOCATION=1; // in meters

    // minimum time to request location updates
    private static final long MIN_TIME_FOR_UPDATES=1000*1; // 1 sec

    //location
    Location location;
    //latitude and longitude
    double latitude,longitude;

    //Declaring a LocationManager
    LocationManager locationManager;

    public LocationTracker(Context context)
    {
        this.con=context;
        checkIfLocationAvailable();
    }

    public Location checkIfLocationAvailable()
    {
        try
        {
            locationManager=(LocationManager)con.getSystemService(LOCATION_SERVICE);
            //check for gps availability
            isGPSOn=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            //check for network availablity
            isNetWorkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if(!isGPSOn && !isNetWorkEnabled)
            {
                isLocationEnabled=false;
                // no location provider is available show toast to user
                Toast.makeText(con,"No Location Provider is Available",Toast.LENGTH_SHORT).show();
            }
            else {
                isLocationEnabled=true;

                // if network location is available request location update
                if(isNetWorkEnabled)
                {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this);
                   if(locationManager!=null)
                   {
                       location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                       if(location!=null)
                       {
                           latitude=location.getLatitude();
                           longitude=location.getLongitude();

                       }
                   }
                }

                if(isGPSOn)
                {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this);

                    if(locationManager!=null)
                    {
                        location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if(location!=null)
                        {
                            latitude=location.getLatitude();
                            longitude=location.getLongitude();
                        }
                    }
                }
            }

        }catch (Exception e)
        {

        }

        return location;
    }

    // call this to stop using location
    public void stopUsingLocation()
    {
        if(locationManager!=null)
        {
            locationManager.removeUpdates(LocationTracker.this);
        }
    }
       // call this to getLatitude
    public double getLatitude()
    {
        if(location!=null)
        {
            latitude=location.getLatitude();
        }
        return latitude;
    }
    //call this to getLongitude
    public double getLongitude()
    {
        if(location!=null)
        {
            longitude=location.getLongitude();
        }
        return longitude;
    }

    public boolean isLocationEnabled() {
        return this.isLocationEnabled;
    }

    //call to open settings and ask to enable Location
    public void askToOnLocation()
    {
        AlertDialog.Builder dialog=new AlertDialog.Builder(con);

        //set title
        dialog.setTitle("Settings");
        //set Message
        dialog.setMessage("Location is not Enabled.Do you want to go to settings to enable it?");
        // on pressing this will be called
        dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                con.startActivity(intent);
            }
        });

        //on Pressing cancel
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // show Dialog box
        dialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

//layout for MainActivity

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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<Button
    android:id="@+id/getlocation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="getLocation"
    android:layout_above="@+id/location"/>

    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/location"/>

</RelativeLayout>

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidruler.mymap" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Simple Login Example Android Using SQLite

MainActivity.java

package com.androidruler.databasesample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

EditText uname,pswd;
Button login;
DbHandler db;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname=(EditText)findViewById(R.id.uname);
pswd=(EditText)findViewById(R.id.password);
login=(Button)findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name=uname.getText().toString();
String password=pswd.getText().toString();

int id= checkUser(new User(name,password));
if(id==-1)
{
Toast.makeText(MainActivity.this,”User Does Not Exist”,Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,”User Exist “+name,Toast.LENGTH_SHORT).show();
}
}
});

db=new DbHandler(MainActivity.this);
//inserting dummy users
db.addUser(new User(“Ankur”, “Bansal”));
db.addUser(new User(“Vibhor”, “Tayal”));
db.addUser(new User(“Jatin”, “Garg”));

}

public int checkUser(User user)
{
return db.checkUser(user);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

User.java

package com.androidruler.databasesample;


//this is model class
public class User {

 //variables
 int id;
 String name;
 String password;


 // Constructor with two parameters name and password
 public User(String name,String password)
 {
 this.name=name;
 this.password=password;
 }
 //Parameter constructor containing all three parameters
 public User(int id,String name,String psd)
 {
 this.id=id;
 this.name=name;
 this.password=psd;

 }
 //getting id
 public int getId() {
 return id;
 }
 //setting id
 public void setId(int id) {
 this.id = id;
 }
 //getting name
 public String getName() {
 return name;
 }
 //setting name
 public void setName(String name) {
 this.name = name;
 }

 //getting password
 public String getPassword() {
 return password;
 }

 //setting password
 public void setPassword(String password) {
 this.password = password;
 }
}

DbHandler.java

package com.androidruler.databasesample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

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


public class DbHandler extends SQLiteOpenHelper {

 //all constants as they are static and final(Db=Database)
 //Db Version
 private static final int Db_Version=1;
 //Db Name
 private static final String Db_Name="users";
 //table name
 private static final String Table_Name="user";
 //Creating mycontacts Columns
 private static final String User_id="id";
 private static final String User_name="name";
 private static final String User_password="password";


 //constructor here
 public DbHandler(Context context)
 {
 super(context,Db_Name,null,Db_Version);
 }

 //creating table
 @Override
 public void onCreate(SQLiteDatabase db) {
 // writing command for sqlite to create table with required columns
 String Create_Table="CREATE TABLE " + Table_Name + "(" + User_id
 + " INTEGER PRIMARY KEY," + User_name + " TEXT," + User_password + " TEXT" + ")";
 db.execSQL(Create_Table);
 }

 //Upgrading the Db
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 //Drop table if exists
 db.execSQL("DROP TABLE IF EXISTS " + Table_Name);
 //create the table again
 onCreate(db);
 }

 //Add new User by calling this method
 public void addUser(User usr)
 {
 // getting db instance for writing the user
 SQLiteDatabase db=this.getWritableDatabase();
 ContentValues cv=new ContentValues();
 // cv.put(User_id,usr.getId());
 cv.put(User_name,usr.getName());
 cv.put(User_password,usr.getPassword());

 //inserting row
 db.insert(Table_Name, null, cv);
 //close the database to avoid any leak
 db.close();
 }

 public int checkUser(User us)
 {
 int id=-1;
 SQLiteDatabase db=this.getReadableDatabase();
 Cursor cursor=db.rawQuery("SELECT id FROM user WHERE name=? AND password=?",new String[]{us.getName(),us.getPassword()});
 if(cursor.getCount()>0) {
 cursor.moveToFirst();
 id=cursor.getInt(0);
 cursor.close();
 }
 return id;
 }
}


//layout for MainActivity
activity_main.xml


<LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 android:paddingBottom="@dimen/activity_vertical_margin"
 tools:context=".MainActivity"
 android:orientation="vertical">

 <TextView
 android:id="@+id/totalcount"
 android:layout_margin="10dp"
 android:text="UserName"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
 <EditText
 android:id="@+id/uname"
 android:layout_width="fill_parent"
 android:layout_height="50dp" />

 <TextView
 android:id="@+id/psw"
 android:layout_margin="10dp"
 android:text="Password"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
 <EditText
 android:id="@+id/password"
 android:layout_width="fill_parent"
 android:layout_height="50dp" />


 <Button
 android:id="@+id/login"
 android:padding="20dp"
 android:text="Login"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

</LinearLayout>


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.androidruler.databasesample" >

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

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

</manifest>



 

Android Working With SQLite Database

MainActivity.java

package com.androidruler.databasesample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

ListView allcontacts;
TextView totalcontacts;
ArrayList<String> allusers=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allcontacts=(ListView)findViewById(R.id.contactlist);
totalcontacts=(TextView)findViewById(R.id.totalcount);

DbHandler db=new DbHandler(MainActivity.this);
//inserting contacts
db.addContact(new Contact(“Ankur”,”Bansal”,”123456789″));
db.addContact(new Contact(“Vibhor”,”Tayal”,”267755557″));
db.addContact(new Contact(“Jatin”,”Garg”,”123456789″));

//getting total number of contacts
int total=db.getTotalContacts();
totalcontacts.setText(“Total Contacts “+total);

//Reading all contacts and adding them to list
List<Contact> contacts=db.getAllContacts();
for (Contact ct: contacts)
{
allusers.add(ct.getFname()+” “+ct.getLname());
}

//setting the list to listview
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,allusers);
allcontacts.setAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Contact.java

package com.androidruler.databasesample;

//this is model class
public class Contact {

//variables
int id;
String fname;
String lname;
String contactnumber;

//simple empty Constructor
public Contact()
{

}
//Parameter constructor containing all three parameters
public Contact(int id,String fname,String lname,String contactnumber)
{
this.id=id;
this.fname=fname;
this.lname=lname;
this.contactnumber=contactnumber;
}

//Parameter constructor containing two parameters
public Contact(String fname,String lname,String contactnumber)
{
this.fname=fname;
this.lname=lname;
this.contactnumber=contactnumber;

}
//getting contactnumber
public String getContactnumber() {
return contactnumber;
}
//setting contactnumber
public void setContactnumber(String contactnumber) {
this.contactnumber = contactnumber;
}
//getting lname
public String getLname() {
return lname;

}
//setting lname
public void setLname(String lname) {
this.lname = lname;
}
//getting fname
public String getFname() {
return fname;
}
//setting fname
public void setFname(String fname) {
this.fname = fname;
}
//getting id
public int getId() {
return id;
}
//setting id
public void setId(int id) {
this.id = id;
}

}

DbHandler.java

package com.androidruler.databasesample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;
public class DbHandler extends SQLiteOpenHelper {

//all constants as they are static and final(Db=Database)
//Db Version
private static final int Db_Version=1;
//Db Name
private static final String Db_Name=”contactscontainer”;
//table name
private static final String Table_Name=”mycontacts”;
//Creating mycontacts Columns
private static final String Contact_id=”id”;
private static final String Contact_fname=”fname”;
private static final String Contact_lname=”lname”;
private static final String Contact_number=”contactnumber”;

//constructor here
public DbHandler(Context context)
{
super(context,Db_Name,null,Db_Version);
}

//creating table
@Override
public void onCreate(SQLiteDatabase db) {
// writing command for sqlite to create table with required columns
String Create_Table=”CREATE TABLE ” + Table_Name + “(” + Contact_id
+ ” INTEGER PRIMARY KEY,” + Contact_fname + ” TEXT,” + Contact_lname +
” TEXT,” + Contact_number + ” TEXT” + “)”;
db.execSQL(Create_Table);
}

//Upgrading the Db
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop table if exists
db.execSQL(“DROP TABLE IF EXISTS ” + Table_Name);
//create the table again
onCreate(db);
}

//Add new Contact by calling this method
public void addContact(Contact contact)
{
// getting db instance for writing the contact
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(Contact_fname,contact.getFname());
cv.put(Contact_lname,contact.getLname());
cv.put(Contact_number,contact.getContactnumber());

//inserting row
db.insert(Table_Name, null, cv);
//close the database to avoid any leak
db.close();
}

//getting contact according to contact id
public Contact getContact(int id)
{
// getting db instance for reading the contact
SQLiteDatabase db=this.getReadableDatabase();
//writing query for getting contact according to id
Cursor cursor=db.query(Table_Name,new String[]{Contact_id,Contact_fname,Contact_lname,Contact_number},Contact_id + “=?” ,
new String[] { String.valueOf(id)},null,null,null,null);
if(cursor!=null)
cursor.moveToFirst();

Contact contact=new Contact(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2),
cursor.getString(3));
return contact;
}

//this will all the contact from the table
public List<Contact> getAllContacts()
{
List<Contact> contactList=new ArrayList<Contact>();
//query to select all contacts from table
String selectAllContact=”SELECT * FROM ” + Table_Name;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectAllContact, null);

// move cursor to first and use loop to add all the contacts to list
if(cursor.moveToFirst())
{
do {
Contact contact =new Contact();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setFname(cursor.getString(1));
contact.setLname(cursor.getString(2));
contact.setContactnumber(cursor.getString(3));
//add contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}

return contactList;
}

//get total contacts in the table
public int getTotalContacts()
{
String totalcontacts= “SELECT * FROM ” + Table_Name;
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery(totalcontacts,null);

//getting total number of rows from cursor
return cursor.getCount();
}

// Updating contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(Contact_fname, contact.getFname());
values.put(Contact_lname, contact.getLname());

// updating row with updated contact values
return db.update(Table_Name, values, Contact_id + ” = ?”,
new String[] { String.valueOf(contact.getId()) });
}

// Deleting contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Table_Name, Contact_id + ” = ?”,
new String[] { String.valueOf(contact.getId()) });
db.close();
}
}

//layout for MainActivity.java
actvity_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" 
 tools:context=".MainActivity">

<ListView
android:id=”@+id/contactlist”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”></ListView>

<TextView
android:layout_below=”@+id/contactlist”
android:layout_margin=”10dp”
android:id=”@+id/totalcount”
android:text=”@string/hello_world”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />

</RelativeLayout>

 

Working with ViewPager as A Images Slider

Working with ViewPager to show image Slider.
Following are required:-

1  Activity class containing viewpager.
2  Adapter class to be set to viewpager.
3  Fragment class whose view will be displayed in viewpager.



// its the Main Activity containing ViewPager
MainActivity.java
package com.androidruler.imageslider;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

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

public class MainActivity extends AppCompatActivity {

    ViewPager pager;
    List<Fragment> fragments;
    // list containing id's of images we want to show in viewpager 
    ArrayList<Integer> images=new ArrayList<Integer>(){{
        add(R.drawable.wonder1);
        add(R.drawable.wonder2);
        add(R.drawable.wonder3);
        add(R.drawable.wonder4);
        add(R.drawable.wonder5);
        add(R.drawable.wonder6);
        add(R.drawable.wonder7);
    }};
    PagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         pager = (ViewPager) findViewById(R.id.viewPager);
        
        //method to create the required fragments to show in viewpager and return as a fragment list
        fragments=getFragments();
        adapter=new PagerAdapter(getSupportFragmentManager(),fragments);
        pager.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
      //  getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    } 
    
    
   
 // Adapter class which is set to viewpagger which uses list to show fragments     in viewpagger
    class PagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragments;
        public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
       public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

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

    
    //method to get list of fragments to be displayed in viewpager 
    private List<Fragment> getFragments() {
        List<Fragment> fList = new ArrayList<Fragment>();
        for (int i = 0; i < images.size(); i++) {
            fList.add(MyImageSlider.newInstance(images.get(i)));
        }
        return fList;
    }
}

//Fragment class
MyImageSlider.java
package com.androidruler.imageslider;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

// its the fragment from where we create fragments
public class MyImageSlider extends Fragment {

    int imageid;

// static method to create the MyImageSlider Fragment containing image
    public  static MyImageSlider newInstance(int id)
    {
        MyImageSlider slider=new MyImageSlider();
        Bundle b=new Bundle();
        b.putInt("imageid", id);
        slider.setArguments(b);
        return slider;
    }


// get the image id from fragment in this method although we can also get in onCreateView.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageid=getArguments().getInt("imageid");
    }


// this method returns the view containing the required which is set while creating instance of fragment
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.adapterview, container, false);
        ImageView iv=(ImageView)view.findViewById(R.id.myimage);

        iv.setImageResource(imageid);

        return view;
    }
}'


//layout for MainActivity.java
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"  
    tools:context=".MainActivity">
    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>'



//layout for MyImageSlider
adapterview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/myimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>'

Android Custom Listview with EditText

For Custom Listview we need the following:-

  1. MainActivity class containing  Listview and will be the main screen.
  2. Create Model class to save data for each row like in this example i created MyItem class
  3. Pass this Model class object to Arraylist to generate each row item of Listview.
  4. Create CustomAdapter class to have view for each row as required in this example i created MyAdapter class to generate view for each row.
  5. We need two layout one for MainActivity class containing listview and other for CustomAdapter which we need for each row of listview. we can create view for CustomAdapter according to our requirement.

//Main Activity

MainActivity.java

package com.androidruler.customlistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView mainactivity;
    // creating arraylist of MyItem type to set to adapter
    ArrayList<MyItem> myitems=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainactivity=(ListView)findViewById(R.id.mainactivitylistview);
   //Adding data i.e images and title to be set to adapter to populate list view
   //here i am passing image id from drawable and string as to be set as title as    //   a parameter to MyItem Constructor as our ArrayList is type of  MyItem
       
 myitems.add(new MyItem(R.drawable.christ_brazil,"Christ Redeemer: Rio de Janeiro
Brazil"));
 myitems.add(new MyItem(R.drawable.greatwall_china,"Great Wall of China: China"));
 myitems.add(new MyItem(R.drawable.machu_peru,"Machu Picchu: Peru"));
 myitems.add(new MyItem(R.drawable.petra_jorden,"Petra: Jordan"));
 myitems.add(new MyItem(R.drawable.pyramid_mexico,"Pyramid at Chichén Itzá:YucataPeninsula, Mexico"));
 myitems.add(new MyItem(R.drawable.roman_rome,"Roman Colosseum: Rome, Italy"));
 myitems.add(new MyItem(R.drawable.taj_india,"Taj Mahal: Agra, India"));


        //Creating Adapter object for setting to listview
        MyAdapter adapter=new MyAdapter(MainActivity.this,myitems);
        mainactivity.setAdapter(adapter);
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present. 
//getMenuInflater().inflate(R.menu.menu_main, menu);
 //this shows three dots at right corner on click settings open
 return true; }
 @Override 
public boolean onOptionsItemSelected(MenuItem item) {
 // Handle action bar item clicks here. The action bar will
 // automatically handle clicks on the Home/Up button, so long 
// as you specify a parent activity in AndroidManifest.xml. 
int id = item.getItemId();
 //noinspection SimplifiableIfStatement
 if (id == R.id.action_settings)
 { return true; } 
return super.onOptionsItemSelected(item);
 } 
}

//Model Class whose objects we pass in arraylist

MyItem.java

public class MyItem {

    private int imageid;
    private String imageheading="";

    public MyItem(int id,String title)
    {
        imageid=id;
        imageheading=title;
    }

    public int getImageid() {
        return imageid;
    }

    public String getImageheading() {
        return imageheading;
    }

    public void setImageheading(String imageheading) {
        this.imageheading = imageheading;
    }

    public void setImageid(int imageid) {

        this.imageid = imageid;
    }
}



MyAdapter.java

//Custom Adapter class extends Baseadapter
public class MyAdapter extends BaseAdapter {


    Context context;
    ArrayList<MyItem> listforview;
    LayoutInflater inflator=null;
    View v;
    ViewHolder vholder;
    //Constructor
    public MyAdapter(Context con,ArrayList<MyItem> list)
    {
        super();
        context=con;
        listforview=list;
        inflator=LayoutInflater.from(con);
    }

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

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

    //get Object from each position
    @Override
    public Object getItem(int position) {
        return listforview.get(position);
    }

    //Viewholder class to contain inflated xml views
    private  class ViewHolder
    {
        TextView title;
        ImageView image;
    }
    // Called for each view
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        v=convertView;
        if(convertView==null)
        {
            //inflate the view for each row of listview
            v=inflator.inflate(R.layout.myadapter,null);
            //ViewHolder object to contain myadapter.xml elements
            vholder=new ViewHolder();
            vholder.title=(TextView)v.findViewById(R.id.adaptertextview);
            vholder.image=(ImageView)v.findViewById(R.id.adapterimage);
            //set holder to the view
            v.setTag(vholder);
        }
        else
            vholder=(ViewHolder)v.getTag();


        //getting MyItem Object for each position
        MyItem item=(MyItem)listforview.get(position);
//set the id to editetxt important line here as it will be helpful to set text according to position
vholder.title.setId(position);
//setting the values from object to holder views for each row vholder.title.setText(item.getImageheading()); vholder.image.setImageResource(item.getImageid());
        vholder.title.setOnFocusChangeListener(
        new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (!hasFocus) {
                   final int id = v.getId();
                    MyItem item = listforview.get(id);
                   final EditText field = ((EditText) v);
                    listforview.get(id).setImageheading(field.getText().toString());

                }

            }
        }
);
return v; } } 

// layout xml file for MainActivity.java 

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"
    tools:context=".MainActivity">


    <ListView
        android:id="@+id/mainactivitylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="@android:color/black"
        android:dividerHeight="2dp"
android:descendantFocusability="afterDescendants"
></ListView> </RelativeLayout> 


// layout xml file for adapter

 myadapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/adapterimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/adaptertextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidruler.customlistview" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustPan"
 > 
<intent-filter>
 <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 </application>
 </manifest>

Android Working With Listview

To create Listview we need the following:-

  1. MainActivity class containing  Listview and will be the main screen.

 

MainActivity.java

package com.androidruler.simplelistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView mainactivity;
    // creating arraylist of MyItem type to set to adapter
    ArrayList<String> myitems=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainactivity=(ListView)findViewById(R.id.mainactivitylistview);
   //Adding data to arraylist to be passed to ArrayAdapter. u can use arrays also.
 myitems.add("Christ Redeemer: Rio de Janeiro Brazil"));
 myitems.add("Great Wall of China: China");
 myitems.add("Machu Picchu: Peru");
 myitems.add("Petra: Jordan");
 myitems.add("Pyramid at Chichén Itzá:YucataPeninsula, Mexico");
 myitems.add("Roman Colosseum: Rome, Italy");
 myitems.add("Taj Mahal: Agra, India");


        //Creating Adapter object for setting to listview
ArrayAdapter adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,android.R.id.text1,myitems);
 mainactivity.setAdapter(adapter);
 }
 @Override 
public boolean onCreateOptionsMenu(Menu menu) { 
// Inflate the menu; this adds items to the action bar if it is present. 
//getMenuInflater().inflate(R.menu.menu_main, menu); 
//this shows three d ots at right corner on click settings open return true; 
} 
@Override 
public boolean onOptionsItemSelected(MenuItem item) {
 // Handle action bar item clicks here. The action bar will
 // automatically handle clicks on the Home/Up button, so long 
// as you specify a parent activity in AndroidManifest.xml. 
int id = item.getItemId(); 
//noinspection SimplifiableIfStatement if (id == R.id.action_settings) 
{ 
return true; 
} return super.onOptionsItemSelected(item);
 }
 }

//layout file for MainActivity.java
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"
    tools:context=".MainActivity">
    <ListView
        android:id="@+id/mainactivitylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="@android:color/black"
        android:dividerHeight="2dp"></ListView>

</RelativeLayout>



AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidruler.simplelistview" >

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

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

</manifest>

			

Android Custom Listview With Image And Text

For Custom Listview we need the following:-

  1. MainActivity class containing  Listview and will be the main screen.
  2. Create Model class to save data for each row like in this example i created MyItem class
  3. Pass this Model class object to Arraylist to generate each row item of Listview.
  4. Create CustomAdapter class to have view for each row as required in this example i created MyAdapter class to generate view for each row.
  5. We need two layout one for MainActivity class containing listview and other for CustomAdapter which we need for each row of listview. we can create view for CustomAdapter according to our requirement.

 

//Main Activity

MainActivity.java

package com.androidruler.customlistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView mainactivity;
    // creating arraylist of MyItem type to set to adapter
    ArrayList<MyItem> myitems=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainactivity=(ListView)findViewById(R.id.mainactivitylistview);
   //Adding data i.e images and title to be set to adapter to populate list view
   //here i am passing image id from drawable and string as to be set as title as    //   a parameter to MyItem Constructor as our ArrayList is type of  MyItem
       
 myitems.add(new MyItem(R.drawable.christ_brazil,"Christ Redeemer: Rio de Janeiro
Brazil"));
 myitems.add(new MyItem(R.drawable.greatwall_china,"Great Wall of China: China"));
 myitems.add(new MyItem(R.drawable.machu_peru,"Machu Picchu: Peru"));
 myitems.add(new MyItem(R.drawable.petra_jorden,"Petra: Jordan"));
 myitems.add(new MyItem(R.drawable.pyramid_mexico,"Pyramid at Chichén Itzá:YucataPeninsula, Mexico"));
 myitems.add(new MyItem(R.drawable.roman_rome,"Roman Colosseum: Rome, Italy"));
 myitems.add(new MyItem(R.drawable.taj_india,"Taj Mahal: Agra, India"));


        //Creating Adapter object for setting to listview
        MyAdapter adapter=new MyAdapter(MainActivity.this,myitems);
        mainactivity.setAdapter(adapter);
// Handle Listview click
  mainactivity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Perform click events
        
        MyItem myitem=(MyItem)myitems.get(position);
        
        String title=myitem.getImageheading();
    }
});
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present. 
//getMenuInflater().inflate(R.menu.menu_main, menu);
 //this shows three dots at right corner on click settings open
 return true; }
 @Override 
public boolean onOptionsItemSelected(MenuItem item) {
 // Handle action bar item clicks here. The action bar will
 // automatically handle clicks on the Home/Up button, so long 
// as you specify a parent activity in AndroidManifest.xml. 
int id = item.getItemId();
 //noinspection SimplifiableIfStatement
 if (id == R.id.action_settings)
 { return true; } 
return super.onOptionsItemSelected(item);
 } 
}

//Model Class whose objects we pass in arraylist

MyItem.java

public class MyItem {

    private int imageid;
    private String imageheading="";

    public MyItem(int id,String title)
    {
        imageid=id;
        imageheading=title;
    }

    public int getImageid() {
        return imageid;
    }

    public String getImageheading() {
        return imageheading;
    }

    public void setImageheading(String imageheading) {
        this.imageheading = imageheading;
    }

    public void setImageid(int imageid) {

        this.imageid = imageid;
    }
}



MyAdapter.java

//Custom Adapter class extends Baseadapter
public class MyAdapter extends BaseAdapter {


    Context context;
    ArrayList<MyItem> listforview;
    LayoutInflater inflator=null;
    View v;
    ViewHolder vholder;
    //Constructor
    public MyAdapter(Context con,ArrayList<MyItem> list)
    {
        super();
        context=con;
        listforview=list;
        inflator=LayoutInflater.from(con);
    }

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

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

    //get Object from each position
    @Override
    public Object getItem(int position) {
        return listforview.get(position);
    }

    //Viewholder class to contain inflated xml views
    private  class ViewHolder
    {
        TextView title;
        ImageView image;
    }
    // Called for each view
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        v=convertView;
        if(convertView==null)
        {
            //inflate the view for each row of listview
            v=inflator.inflate(R.layout.myadapter,null);
            //ViewHolder object to contain myadapter.xml elements
            vholder=new ViewHolder();
            vholder.title=(TextView)v.findViewById(R.id.adaptertextview);
            vholder.image=(ImageView)v.findViewById(R.id.adapterimage);
            //set holder to the view
            v.setTag(vholder);
        }
        else
            vholder=(ViewHolder)v.getTag();


        //getting MyItem Object for each position
        MyItem item=(MyItem)listforview.get(position);

        //setting the values from object to holder views for each row
        vholder.title.setText(item.getImageheading());
        vholder.image.setImageResource(item.getImageid());

        return v;
    }
}


// layout xml file for MainActivity.java
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"
    tools:context=".MainActivity">


    <ListView
        android:id="@+id/mainactivitylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="@android:color/black"
        android:dividerHeight="2dp"></ListView>

</RelativeLayout>


// layout xml file for adapter
myadapter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/adapterimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/adaptertextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidruler.customlistview" >

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

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

</manifest>