Thursday, 18 August 2016

Android JSON Tutorial

JSON is Javascript Object Notation. Basically it is a part of Javascript programming language. Now a days it is generally use for data exchange between server and client. It is light weight data exchange format and takes lesser memory than xml. Data is stored in JSON as key-value pair.
Basic Format of JSON :

{
"key1":"value1",
"key2":"value2",
"key3":"value3",
....
....
....
....
}

JSON in Android

Android provide two classes which is used to implement JSON functionality in Android .
  1. JSONObject
  2. JSONArray
1) JSONObject : JSONObject is used to convert JSON String to JSON Object and vice a versa. We can also create own JSON object from our raw data. For Example -



JSONObject jsonObj = new JSONObject();
jsonObj.put("name","Sam");
jsonObj.put("age","23");
jsonObj.put("address","USA");

console.log("JSON String",jsonObj.toString());


Result on console : 



{"name":"Sam","age":"23","address":"USA"}

You can also convert JSON string to JSON object by passing json string into the constructor of JSONObject class.



String jsonString = "{'name':'Sam','age':'23','address':'USA'}";
JSONObject jsonObj = new JSONObject(jsonString);


To print key's value you need to call getString('key') method of JSONObject class.



String jsonString = "{'name':'Sam','age':'23','address':'USA'}";
JSONObject jsonObj = new JSONObject(jsonString);
console.log("Name : ",jsonObj.getString("name"));



JSONArray : JSONArray class is used to store multiple JSONObjects .
                     For example :-

                        [{"name":"Sandy"},{"name","Mandy"},{"name":"Sam"}]



String jsonString = "[{'name':'Sandy'},{'name':'Mandy'},{'name':'Sam'}]";
JSONArray arr = new JSONArray(jsonString);
for(int i=0;i<arr.length();i++)
     {
       JSONObject obj = arr.getJSONObject(i); 
       console.log("Name : ",jsonObj.getString("name"));
     }

Wednesday, 17 August 2016

Date in Android

Android uses Java Date api to implement the Date functionality in app. Today every major app have date functionality in it. Like Facebook, Instagram, Youtube etc have date functionality in it. Facebook posts and messages are order according to date. Latest post and messages are on the top position. In this post we learn about Date.

Current Date
public String CurrentDate()
{
   Calendar cal = Calendar.getInstance();
   return String.valueOf(cal.get(Calendar.DAY_OF_MONTH)).trim();
}


Current Month
public String CurrentMonth()
{
 Calendar cal = Calendar.getInstance();
 return String.valueOf(cal.get(Calendar.MONTH)+1).trim();
}


Current Year
public String CurrentYear()
{
 Calendar cal = Calendar.getInstance();
 return String.valueOf(cal.get(Calendar.YEAR)).trim();
}


Current Hour
public String Hour()
{
 Calendar cal = Calendar.getInstance();
 return String.valueOf(cal.get(Calendar.HOUR_OF_DAY)).trim();
}


Current Minute
public String Minute()
{
 Calendar cal = Calendar.getInstance();
 return String.valueOf(cal.get(Calendar.MINUTE)).trim();
}


Current Second
public String Second()
{
 Calendar cal = Calendar.getInstance();
 return String.valueOf(cal.get(Calendar.SECOND)).trim();
}


Current MilliSecond
public String MilliSecond()
{
 Calendar cal = Calendar.getInstance();
 return String.valueOf(cal.get(Calendar.MILLISECOND)).trim();
}


Last Month
public String LastMonth()
{
 Calendar cal = Calendar.getInstance();
 cal.add(Calendar.MONTH ,-1);
 return( new SimpleDateFormat("MM").format(cal.getTime())).trim();
}


Last Year
public String LastYear()
{
    Calendar prevYear = Calendar.getInstance();
    prevYear.add(Calendar.YEAR, -1);
    return String.valueOf(prevYear.get(Calendar.YEAR));
}


Last Date of Month
public String getLastDate(int month, int year)
{
 Calendar cal = Calendar.getInstance();
 // passing month-1 because 0-->jan, 1-->feb... 11-->dec
 cal.set(year, month-1, 1);
 cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
 Date date = cal.getTime();
 //DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/YYYY");
 DateFormat DATE_FORMAT = new SimpleDateFormat("dd");
 return DATE_FORMAT.format(date).trim();
}


Day Name
public String getDayName(int day,int month,int year){
  Date date =null;
  String dateString = String.format("%d-%d-%d", year, month, day);
 try{
     date = new SimpleDateFormat("yyyy-M-d").parse(dateString);
    }
 catch (Exception e) {}
 return new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);
 }


Previous Date
public static String getPreviousDate()
{
 Calendar cal  = Calendar.getInstance();
 //subtracting a day
 cal.add(Calendar.DATE, -1);
 SimpleDateFormat s = new SimpleDateFormat("dd");
 return s.format(new Date(cal.getTimeInMillis()));
 }


Months Names List
public String[] GetMonthsNames()
{
 DateFormatSymbols dfs = new DateFormatSymbols();
 return dfs.getMonths();
}


Tomorrow Date
public int TomorrowDate()
{
 Date date = new Date();
 Calendar cal = Calendar.getInstance();
 cal.setTime(date);
 cal.add(Calendar.DATE, 1);
 return cal.get(Calendar.DATE);
}


Next Month
public int NextMonth(){
 Date date = new Date();
 Calendar cal = Calendar.getInstance();
 cal.setTime(date);
 cal.add(Calendar.DATE, 30);
 return cal.get(Calendar.MONTH)+1;
}


Next Year
public int NextYear()
{
 Date date = new Date();
 Calendar cal = Calendar.getInstance();
 cal.setTime(date);
 cal.add(Calendar.YEAR, 1);
 return cal.get(Calendar.YEAR);
}


Get Unix TimeStamp
public String unixTimestamp(int y, int m, int d) 
{
 month--;
 Date tg = new Date(year, month, day);
 return String.valueOf(tg.getTime() / 1000L);
}


Unix timestamp to Date
public String UNIX(long a)
{
 long timestamp = a * 1000;
 Date date = new Date(timestamp);
 Calendar cal = Calendar.getInstance();
 cal.setTime(date);
 return cal.get(Calendar.DATE)+"/"+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.YEAR);
}



Saturday, 13 August 2016

Turbo charge Android Sqlite Database

In Android insert() method is used to insert record into table. Insert method compiles query every time before inserting the data into table . If there are 1000 records it compiles query 1000 times. So to eliminate this problem android provides compileStatement(). It compile query only one and then it insert records only.

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:orientation="vertical"
>

    <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Normal Insertion"
        android:id="@+id/normalinsert"
        />
     <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Fast Insertion"
        android:id="@+id/fastinsert"
        />

    <TextView
        android:layout_width="wrap_content"
        android:id="@+id/tv"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>


Database.java
package com.example.turbochargedatabase;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class Database {

 private static final String dbName="TURBOCHARGE";
 Connect c;
 Context context;
 SQLiteDatabase sld;
 public Database(Context context){
  this.context=context;
 }
 private class Connect extends SQLiteOpenHelper
 {

  public Connect(Context context, String name, CursorFactory factory,
    int version) {
   super(context, name, factory, version);
   // TODO Auto-generated constructor stub
  }

  @Override
  public void onCreate(SQLiteDatabase arg0) {
   // TODO Auto-generated method stub
   arg0.execSQL("CREATE TABLE INFO (ID INTEGER PRIMARY KEY AUTOINCREMENT,INCC TEXT)");
  }

  @Override
  public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
   // TODO Auto-generated method stub
   
  }
  
 }
 
 public void NormalInsert(){
  ContentValues cv;
  for(int i=0;i<2500;i++){
   cv =new ContentValues();
   cv.put("INCC", String.valueOf(i));
   sld.insert("INFO", null, cv);
  }
 }
 public void FastInsert(){
   try{
  String sql = "INSERT INTO INFO(INCC) VALUES(?)";
   SQLiteStatement statement = sld.compileStatement(sql);
   sld.beginTransaction();
  for(int i=0;i<2500;i++)
     {
     statement.clearBindings();
     statement.bindString(1, String.valueOf(i));
     statement.execute();
     }
   
   sld.setTransactionSuccessful();
   }catch(Exception e){}
   finally{sld.endTransaction();}
 }
 public void open(){
  c = new Connect(context, dbName, null, 1);
  sld = c.getWritableDatabase();
 }
 public void close(){
  sld.close();
  c.close();
 }
}



MainActivity.java
package com.example.turbochargedatabase;

import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener {

 TextView tv;
 Database db = new Database(this);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv =(TextView)findViewById(R.id.tv);
        findViewById(R.id.normalinsert).setOnClickListener(this);
        findViewById(R.id.fastinsert).setOnClickListener(this);
        
    }

    private class Insert extends AsyncTask{
     Date date1,date2;
     ProgressDialog dg;
     boolean isk;
     public  Insert(boolean isk){
      this.isk = isk;
     }
  @Override
  protected void onPostExecute(Void result) {
   // TODO Auto-generated method stub
   super.onPostExecute(result);
   dg.dismiss();
   Calendar cal2 = Calendar.getInstance();
         cal2.set(ManageDate.Year(), ManageDate.Month(), ManageDate.Date(),ManageDate.Hour() , ManageDate.Minute(), ManageDate.Second());
         date2 = cal2.getTime();
         long milliSec1 = date1.getTime();
         long milliSec2 = date2.getTime();
  
         long timeDifInMilliSec;
         if(milliSec1 >= milliSec2)
         {
             timeDifInMilliSec = milliSec1 - milliSec2;
         }
         else
         {
             timeDifInMilliSec = milliSec2 - milliSec1;
         }
         long timeDifSeconds = timeDifInMilliSec / 1000;
         
    tv.setText("It takes "+timeDifSeconds+" seconds to insert");
  }

  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   super.onPreExecute();
   Calendar cal1 = Calendar.getInstance();
         cal1.set(ManageDate.Year(), ManageDate.Month(), ManageDate.Date(),ManageDate.Hour() , ManageDate.Minute(), ManageDate.Second());
          date1 = cal1.getTime();
     dg = new ProgressDialog(MainActivity.this);
      dg.setMessage("Loading...");
      dg.setCancelable(false);
      dg.show();
      
  }

  @Override
  protected Void doInBackground(Void... arg0) {
   // TODO Auto-generated method stub
   db.open();
   if(isk)
      db.NormalInsert();
   else db.FastInsert();
      db.close();
   return null;
  }
     
    }

   
 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  switch(arg0.getId()){
  case R.id.normalinsert:
   new Insert(true).execute();
   break;
  case R.id.fastinsert:
   new Insert(false).execute();
   break;
  }
 }
}


Create and Whatsapp Image with Custom Text in Android

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

    <Button
        android:id="@+id/sendmsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Create and send Image" />

</LinearLayout>


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.customtextimage"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.STORAGE" />
    
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  
    <application
        android:allowBackup="true"
        android:icon="@drawable/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>



MainActivity.java

package com.example.customtextimage;

import java.io.File;
import java.io.FileOutputStream;
android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Paint.Align;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn= (Button)findViewById(R.id.sendmsg);
        btn.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    sendMessgae();
   }
  });
    }
    
    private void sendMessgae(){
     
     String text="Hello World!";
     String imagePath= Environment.getExternalStorageDirectory()+File.separator+System.currentTimeMillis()+".png";
     try {
       Bitmap  b = Bitmap.createBitmap(1000,1000,Bitmap.Config.ARGB_8888);
      Canvas cv=new Canvas(b);
       cv.drawColor(Color.WHITE);
      Paint  paint=new Paint();
       paint.setColor(Color.BLACK);
       paint.setTextAlign(Align.CENTER);
       paint.setTextSize(50);
       paint.setStyle(Paint.Style.FILL);
       paint.setAntiAlias(true);
       paint.setTextSize(50);
       cv.drawText(text, 500, 500, paint);
    paint.setTextSize(34);
         FileOutputStream stream = new FileOutputStream(imagePath); //create your FileOutputStream here
       b.compress(CompressFormat.JPEG, 85, stream);
       b.recycle();
       
       // Send image to whatsapp
       Uri imageUri = Uri.parse(imagePath);
       Intent shareIntent = new Intent();
       shareIntent.setAction(Intent.ACTION_SEND);
       //Target whatsapp:
       shareIntent.setPackage("com.whatsapp");
       //Add text and then Image URI
       shareIntent.putExtra(Intent.EXTRA_TEXT, text);
       shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
       shareIntent.setType("image/jpeg");
       shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

       try {
           startActivity(shareIntent);
       } catch (android.content.ActivityNotFoundException ex) {
           Toast.makeText(getApplicationContext(), "Whatsapp have not been installed.", 1000).show();
       }
     }catch(Exception e){}
    }    
}



Style HTML Checkbox

<!DOCTYPE html>
<html>
<head>
 <title>Style HTML Checkbox</title>
</head>
<body>
<style>

div{margin:30px;}
label {
    display: inline-block;
    cursor: pointer;
    position: relative;
    font-size: 13px;
    margin-right:10px;
}
label:before {
    content:"";
    display: inline-block;
    width:25px;
    height: 25px;
    margin-right: 10px;
    position: absolute;
    left: 0;
    bottom: 1px;
    background-color: #fff;
    box-shadow: inset 0px 1px 3px 0px rgba(0, 0, 0, .3), 0px 1px 2px 0px rgba(255, 255, 255, .8);
    border-radius: 3px;
}
input[type=checkbox] {
    display: none;
}
input[type='checkbox']:checked + label:before {
    content:"\2713";
     position:absolute;
    font-size: 18px;
    color: #000;
    text-align:center;
    
}

</style>
<div>
<input  type="checkbox" class="checkbox" checked="true" />
<label></label>
</div>
</body>
</html>

HTML Custom Dropdown using jQuery

HTML provides <select> tag to select value using its default dropdown. But some times there is a need for Custom dropdown. So in this tutorial we are going to build custom dropdown.

<!DOCTYPE html>
<html>
<head>
 <title>Custom Drop Down</title>
 <style>
 .dropdown {
    display: inline-block;
    margin: 10px;
    position: relative;
    padding: 0;
    border: 0;
    border-radius: 5px;
    font-size: 24px;
    font-weight: 400;
    background: #26A69A;
    color: #FFF;
    box-shadow: 0px 8px 17px 0px rgba(0, 0, 0, 0.2), 0px 6px 20px 0px rgba(0, 0, 0, 0.19);
    width:120px;
}
.dropdown > input {
    display: none;
    position: fixed;
    z-index: -2;
}
.dropdown > label {
    display: inline-block;
    max-width: 100%;
    margin-bottom: 5px;
    font-weight: 700;
}
.drop-ttl {
    font-weight: 400;
    padding: 5px 20px;
}
.dropdown ul {
    width: 100%;
    font-weight: 400;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 0;
    text-align: center;
    list-style-type: none;
    background: #FFF;
    color: #26A69A;
    box-shadow: 0px 8px 17px 0px rgba(0, 0, 0, 0.2), 0px 6px 20px 0px rgba(0, 0, 0, 0.19);
    border-radius: 5px;
}
.dropdown ul >li {
    padding: 5px 20px;
    cursor: pointer;
}
.dropdown ul > li > a {
    color: inherit;
    outline: 0;
    text-decoration: none;
    cursor: pointer;
}
.dropdown ul > li:hover{
    background:#DEDEDE;
}
input[type="checkbox"]:checked ~ label > ul {
    display:none;
}

 </style>
</head>
<body>
<div class="dropdown">
    <input id="checkbox1" type="checkbox" name="checkbox" checked="">
    <label for="checkbox1">
        <div class="drop-ttl">Local</div>
        <ul class="dcf">
            <li><a>Local</a></li>
            <li><a>Regional</a></li>
            <li><a>National</a></li>
         </ul>
    </label>
</div>

 <script   src="https://code.jquery.com/jquery-2.2.4.js"  ></script>
 <script>
 $(function(){
    $('.dcf').on("click","li a",function(){
      $('.drop-ttl').html($(this).html());
    })
  });
</script>
</body>
</html>

Friday, 12 August 2016

Get Frame from Video in Android

Lets retrive image from Video in Android.

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:orientation="vertical"
    >

    <Button
        android:id="@+id/openfile"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text=" Open Video File " />

    <ImageView
        android:id="@+id/img"
       android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout> 


Write permission to AndroidManifest.xml


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


MainActivity.java


package com.example.getvideoframe;

import java.net.URISyntaxException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap; 
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;



public class MainActivity extends Activity {

 private static final int FILE_SELECT_CODE=11;
 ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button)findViewById(R.id.openfile);
        imageView=(ImageView)findViewById(R.id.img);
        btn.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    showFileChooser();
   }
  });
    }

    
    private void showFileChooser() {
     Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
     intent.setType("*/*"); 
     intent.addCategory(Intent.CATEGORY_OPENABLE);

     try {
         startActivityForResult(
                 Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
     } catch (android.content.ActivityNotFoundException ex) {
         // Potentially direct the user to the Market with a Dialog
         Toast.makeText(this, "Please install a File Manager.", 
                 Toast.LENGTH_SHORT).show();
     }
 }
    
    @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if(requestCode==FILE_SELECT_CODE&&resultCode == RESULT_OK){
       
             // Get the Uri of the selected file 
             Uri uri = data.getData();
             try{
            String   path = getPath(this, uri);
             if(path==null) return;
             
             Bitmap map= retriveVideoFrameFromVideo(path);
             imageView.setImageBitmap(map);
             }
             
             catch(Exception e){}
            
  }
 }


 public static Bitmap retriveVideoFrameFromVideo(String p_videoPath)
           
    {
        Bitmap m_bitmap = null;
        MediaMetadataRetriever m_mediaMetadataRetriever = null;
        try
        {
            m_mediaMetadataRetriever = new MediaMetadataRetriever();
            m_mediaMetadataRetriever.setDataSource(p_videoPath);
            m_bitmap = m_mediaMetadataRetriever.getFrameAtTime();
        }
        catch (Exception m_e)
        {
        }
        finally
        {
            if (m_mediaMetadataRetriever != null)
            {
                m_mediaMetadataRetriever.release();
            }
        }
        return m_bitmap;
    }
 
 public  String getPath(Context context, Uri uri) throws URISyntaxException {
     if ("content".equalsIgnoreCase(uri.getScheme())) {
         String[] projection = { "_data" };
         Cursor cursor = null;

         try {
             cursor = context.getContentResolver().query(uri, projection, null, null, null);
             int column_index = cursor.getColumnIndexOrThrow("_data");
             if (cursor.moveToFirst()) {
                 return cursor.getString(column_index);
             }
         } catch (Exception e) {
             // Eat it
         }
     }
     else if ("file".equalsIgnoreCase(uri.getScheme())) {
         return uri.getPath();
     }

     return null;
 } 
}



Thursday, 11 August 2016

Custom Listview with Imageview and Textview in Android

Android provides Listview to display items in list. But there is drawback on Android basic Listview, you can not a customize it. So to make own Custom Listview you need to implement own code.

In this tutorial we are going to implement Custom Listview using BaseAdapter class.BaseAdapter class provides a set of methods which is used to create the custom list.


First create 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:orientation="vertical"
    >

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:textStyle="bold"
        android:text=" Countries " />

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

</LinearLayout> 

Now create a layout for list item which is displayed in Listview as a row. Create new file in layout folder named a list_row.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="wrap_content"
    android:orientation="horizontal"
    >

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


 <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:textStyle="bold"  />

</LinearLayout> 


Now create Model named as CountryModel.java. This is used to send data between Activity and Adapter class.





public class CountryModel {

private int image;
private String countryName;

public void setImage(int a)
{
image = a;
} 

public void setCountry(String a)
{
countryName = a;
} 
public int getImage()
{
return  image;
} 
public String getCountry()
{
return  countryName;
} 
} 


Now create Adapter class named as CountryAdapter.java.




public class CountryAdapter extends BaseAdapter{

ArrayList<CountryModel>  list;
LayoutInflater inflater;
ViewHolder holder;
public CountryAdapter(Context c,ArrayList<CountryModel> list){
this.list=list;
inflater=(LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

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

@Override
public Object getItem(int arg0) {
return list.get(arg0);
}

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

@Override
public View getView(int position,View convertView,ViewGroup arg2) {

View vi = convertView;

if (convertView==null){
           
         vi = inflater.inflate(R.layout.list_row, null);
         
         holder = new ViewHolder();
         holder.image = (ImageView) vi.findViewById(R.id.img);
         holder.countryname=(TextView)vi.findViewById(R.id.tv);
         
         vi.setTag( holder );
     }
     else 
         holder=(ViewHolder)vi.getTag();
     CountryModel m = list.get(position);
     holder.image.setImageResource(m.getImage());
     holder.countryname.setText(m.getCountry());
 return vi;
}

public static class ViewHolder{
   
      public ImageView image;
      public TextView countryname;
   }
}


Now create MainActivity.java file and assign custom list to listview.





public class MainActivity  extends Activity {

CountryModel model;

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayList list = new ArrayList();
        model=new CountryModel();
        model.setImage(R.drawable.flag_canada);
        model.setCountry("Canada");
        list.add(model);
        model=new CountryModel();
        model.setImage(R.drawable.flag_france);
        model.setCountry("France");
        list.add(model);
        model=new CountryModel();
        model.setImage(R.drawable.flag_india);
        model.setCountry("India");
        list.add(model);
        model=new CountryModel();
        model.setImage(R.drawable.flag_poland);
        model.setCountry("Poland");
        list.add(model);
        model=new CountryModel();
        model.setImage(R.drawable.flag_russia);
        model.setCountry("Russia");
        list.add(model);
        model=new CountryModel();
        model.setImage(R.drawable.flag_uk);
        model.setCountry("UK");
        list.add(model);
        model=new CountryModel();
        model.setImage(R.drawable.flag_usa);
        model.setCountry("Usa");
        list.add(model);
        
        ListView lv =(ListView)findViewById(R.id.listview);
        CountryAdapter adapter =new CountryAdapter(this, list);
        lv.setAdapter(adapter);
        
  }
}




Vibrate Mobile Device Using HTML5

HTML5 provide different sets on API like Camera, Geo Location, Battery and many more APIs. Vibrate api is one if them. Today every mobile vendor provide vibrating functionality in its device.

We can implements vibrate functionality with two type. First is to use native api, like Android, IPhone, Blackberry its own sets of native api for vibrating functionality. But there is drawback of this. You need to learn its native language like Java, Objective-c or Swift to implements this.

Here are the implementation of Native implementation of vibrate mobile device.




Second method is to use HTML5 API. Which is platform independent. So in this tutorial we use HTML5 API to implement this functionality. HTML5 API runs only in browser either it is Mobile browser or Desktop Browser. You need that Browser which support HTML5 APIs.


Vibrate does not work in Desktop/Laptop Browser because there is not hardware for vibration in desktop/laptop.


Browser Support of Vibrate API

Before we use the api , we need check whether vibrating functionality is supported by browser or not. Then we use  vibrating functionality.

if ("vibrate" in navigator) {
// vibration API supported
}


To check and use prefixed versions, you can use code such as:


navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
if (navigator.vibrate) {
// vibration API supported
}


Implement Vibrate functionality

Vibration is set by passing milliseconds in vibrate method. Then device vibrate upto that value which is passed in vibrate method. For ex. 1000 milli seconds, device will vibrate for 1 second.


navigator.vibrate(1000);

Vibrate method also accept array of vibration and delay time(milliseconds)

navigator.vibrate([1000, 500, 1000]);

The above code vibrate for 1000ms , the wait for 500ms and then vibrate again for 1000ms. You can any number of arguments in an array.