Friday, 14 November 2014

Draw Route on MapV2

Create class GMapV2Direction.java

package com.exampledrawrouteonmap.act;

import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.google.android.gms.maps.model.LatLng;


public class GMapV2Direction {

public final static String MODE_DRIVING = "driving";
public final static String MODE_WALKING = "walking";

public GMapV2Direction() { }

public Document getDocument(LatLng start, LatLng end, String mode) {

//Implement THREADING concept here  ###

String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode=driving";

try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, localContext);

InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public String getDurationText (Document doc) {
NodeList nl1 = doc.getElementsByTagName("duration");
       Node node1 = nl1.item(0);
       NodeList nl2 = node1.getChildNodes();
       Node node2 = nl2.item(getNodeIndex(nl2, "text"));
       Log.i("DurationText", node2.getTextContent());
return node2.getTextContent();
}

public int getDurationValue (Document doc) {
NodeList nl1 = doc.getElementsByTagName("duration");
       Node node1 = nl1.item(0);
       NodeList nl2 = node1.getChildNodes();
       Node node2 = nl2.item(getNodeIndex(nl2, "value"));
       Log.i("DurationValue", node2.getTextContent());
return Integer.parseInt(node2.getTextContent());
}

public String getDistanceText (Document doc) {
NodeList nl1 = doc.getElementsByTagName("distance");
       Node node1 = nl1.item(0);
       NodeList nl2 = node1.getChildNodes();
       Node node2 = nl2.item(getNodeIndex(nl2, "text"));
       Log.i("DistanceText", node2.getTextContent());
return node2.getTextContent();
}

public int getDistanceValue (Document doc) {
NodeList nl1 = doc.getElementsByTagName("distance");
       Node node1 = nl1.item(0);
       NodeList nl2 = node1.getChildNodes();
       Node node2 = nl2.item(getNodeIndex(nl2, "value"));
       Log.i("DistanceValue", node2.getTextContent());
return Integer.parseInt(node2.getTextContent());
}


public String getStartAddress (Document doc) {
NodeList nl1 = doc.getElementsByTagName("start_address");
       Node node1 = nl1.item(0);
       Log.i("StartAddress", node1.getTextContent());
return node1.getTextContent();
}

public String getEndAddress (Document doc) {
NodeList nl1 = doc.getElementsByTagName("end_address");
       Node node1 = nl1.item(0);
       Log.i("StartAddress", node1.getTextContent());
return node1.getTextContent();
}

public String getCopyRights (Document doc) {
NodeList nl1 = doc.getElementsByTagName("copyrights");
       Node node1 = nl1.item(0);
       Log.i("CopyRights", node1.getTextContent());
return node1.getTextContent();
}

public ArrayList<LatLng> getDirection (Document doc) {
NodeList nl1, nl2, nl3;
       ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
       nl1 = doc.getElementsByTagName("step");   
       if (nl1.getLength() > 0) {
           for (int i = 0; i < nl1.getLength(); i++) {
               Node node1 = nl1.item(i);
               nl2 = node1.getChildNodes();

               Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
               nl3 = locationNode.getChildNodes();
               Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
               double lat = Double.parseDouble(latNode.getTextContent());
               Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
               double lng = Double.parseDouble(lngNode.getTextContent());
               listGeopoints.add(new LatLng(lat, lng));

               locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
               nl3 = locationNode.getChildNodes();
               latNode = nl3.item(getNodeIndex(nl3, "points"));
               ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
               for(int j = 0 ; j < arr.size() ; j++) {
               listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
               }

               locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
               nl3 = locationNode.getChildNodes();
               latNode = nl3.item(getNodeIndex(nl3, "lat"));
               lat = Double.parseDouble(latNode.getTextContent());
               lngNode = nl3.item(getNodeIndex(nl3, "lng"));
               lng = Double.parseDouble(lngNode.getTextContent());
               listGeopoints.add(new LatLng(lat, lng));
           }
       }
    
       return listGeopoints;
}

private int getNodeIndex(NodeList nl, String nodename) {
for(int i = 0 ; i < nl.getLength() ; i++) {
if(nl.item(i).getNodeName().equals(nodename))
return i;
}
return -1;
}

private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;

LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
poly.add(position);
}
return poly;
}

}


then this is the MainActivity.java

package com.exampledrawrouteonmap.act;

import java.util.ArrayList;

import org.w3c.dom.Document;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class MainActivity extends FragmentActivity {

private static final String TAG ="MainActivity";
GoogleMap mMap;
GMapV2Direction md;

/*LatLng fromPosition = new LatLng(12.914788 , 77.610106);
LatLng toPosition = new LatLng(12.94231 , 77.59739); */

LatLng fromPosition = new LatLng(23.037446,72.566325);
LatLng toPosition = new LatLng(23.054590 , 72.519743); 

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

md = new GMapV2Direction();
mMap = ((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.the_map)).getMap();

// LatLng coordinates = new LatLng(12.914788 , 77.610106);
LatLng coordinates = new LatLng(23.037446,72.566325);

mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setAllGesturesEnabled(true);
mMap.setTrafficEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));

mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));

new showRoute().execute();
}

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

private class showRoute extends AsyncTask<Void, Void, Document>{

Document doc;
PolylineOptions rectLine;

@Override
protected Document doInBackground(Void... params) {

doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);

ArrayList<LatLng> directionPoint = md.getDirection(doc);
rectLine = new PolylineOptions().width(3).color(Color.RED);

for(int i = 0 ; i < directionPoint.size() ; i++) {
           rectLine.add(directionPoint.get(i));
}

return null;
}

@Override
protected void onPostExecute(Document result) {

mMap.addPolyline(rectLine);
}

}

}

And last here is my manifest.xml file

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    
    <permission android:name="com.prabhakar.permission.MAPS_RECEIVE"
         android:protectionLevel="signature"/>

    <uses-permission android:name="com.prabhakar.permission.MAPS_RECEIVE" />    
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
    <uses-feature android:glEsVersion="0x00020000"
        android:required="true"/>

    <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>
        
       <!-- to get this API go to https://code.google.com/apis/console/ 
       and create api for this pacakge from SHA1 key
       Release key :- AIzaSyAATtJF2N3Hk5o_-QkDfq9sfi10sau4_Ys
        Debug key :- AIzaSyAfxRwKM9g3TnOk6rsJtAvO8qdz6bqY2z4
        --> 
           <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyAfxRwKM9g3TnOk6rsJtAvO8qdz6bqY2z4" />
             <meta-data android:name="com.google.android.gms.version" 
            android:value="@integer/google_play_services_version" />
    </application>


</manifest>

Use Third party API in Android

Create class MySSLSocketFactory.java

package com.example.authdemo;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;

public class MySSLSocketFactory extends SSLSocketFactory{
    SSLContext sslContext = SSLContext.getInstance("TLS");

    /**
     * @param truststore
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws KeyStoreException
     * @throws UnrecoverableKeyException
     */
    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException,
            KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] {
            tm
        }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
            throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }

}


and MainActivity.java

package com.example.authdemo;

import java.security.KeyStore;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

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

txt = (TextView)findViewById(R.id.txt);
new Thread(new Runnable() {
@Override
public void run() {
String responseBody = getData("your thirdparty url");
if(responseBody != null){
// Log.e("responseBody", responseBody);
Log.i("MainActi","Response....."+responseBody);
}
}
}).start();
}
public String getData(String url) {
String responseBody = null;
HttpUriRequest request = new HttpGet(url); // Or HttpPost(), depends on your needs  
String credentials = "username:password";
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);  
request.addHeader("Authorization", "Basic " + base64EncodedCredentials);

HttpClient httpclient = getNewHttpClient();  
try {
HttpResponse httpResponse = httpclient.execute(request);
int code = httpResponse.getStatusLine().getStatusCode();
Log.e("responseCode ", String.valueOf(code));
if(code ==  HttpStatus.SC_OK){
responseBody = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
}
return responseBody; 
}
/****
     * HTTPS
     * 
     * @return DefaultHttpClient
     */
    public static DefaultHttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }
}

JSON Parsing Example

Create JSONParser.java class for parsing api url

package com.examplejsonparsing.act;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
  static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";
  // constructor
  public JSONParser() {
  }
  public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
      // defaultHttpClient
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);
      HttpResponse httpResponse = httpClient.execute(httpPost);
      HttpEntity httpEntity = httpResponse.getEntity();
      is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          is, "iso-8859-1"), 8);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "n");
      }
      is.close();
      json = sb.toString();
    } catch (Exception e) {
      Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
      jObj = new JSONObject(json);
    } catch (JSONException e) {
      Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
  }

}

then in main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/uid"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/uid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_alignParentTop="true"
        android:layout_marginTop="76dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


</LinearLayout>

and last is MainActivity.java file

package com.examplejsonparsing.act;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
  //URL to get JSON Array
  private static String url = "http://10.0.2.2/JSON/";
  //JSON Node Names
  private static final String TAG_USER = "user";
  private static final String TAG_ID = "id";
  private static final String TAG_NAME = "name";
  private static final String TAG_EMAIL = "email";
  JSONArray user = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    // Creating new JSON Parser
    JSONParser jParser = new JSONParser();
    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
      // Getting JSON Array
      user = json.getJSONArray(TAG_USER);
      JSONObject c = user.getJSONObject(0);
      // Storing  JSON item in a Variable
      String id = c.getString(TAG_ID);
      String name = c.getString(TAG_NAME);
      String email = c.getString(TAG_EMAIL);
      
      //Importing TextView
      final TextView uid = (TextView)findViewById(R.id.uid);
      final TextView name1 = (TextView)findViewById(R.id.name);
      final TextView email1 = (TextView)findViewById(R.id.email);
      //Set JSON Data in TextView
      uid.setText(id);
      name1.setText(name);
      email1.setText(email);
  } catch (JSONException e) {
    e.printStackTrace();
  }
    }
}

and don't forget to give permission in manifest.xml file

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

Android Interface Use Example

How we can use interface in Android application.

create activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <EditText 
        android:id="@+id/edtname"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:hint="Enter name"/>
    <Button 
        android:id="@+id/btnadd"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Add item"/>
    <ListView 
        android:id="@+id/lst"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:background="@android:color/black"></ListView>


</LinearLayout>

then create lstraw.xml for listview dynamic raw

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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="Delete" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/button1"
        android:layout_centerVertical="true"
        android:text="TextView" />

</RelativeLayout>

below is MainActivity.java

package com.exampleinterfaceexample.act;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity{
ArrayList<String> myary;
ListView lst;
MyListAdapter mylstadp;
EditText edtname;
Button btnadd;
String strname;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lst = (ListView)findViewById(R.id.lst);
edtname = (EditText)findViewById(R.id.edtname);
btnadd = (Button)findViewById(R.id.btnadd);
myary = new ArrayList<String>();
myary.add("Android");
myary.add("Iphone");
myary.add("Windows");
myary.add("Blackberry");
myary.add("Ipad");
mylstadp = new MyListAdapter(getApplicationContext(), myary);
lst.setAdapter(mylstadp);
mylstadp.setListeners(new MyInterface() {
@Override
public void rowDeleted(Integer pos) {
// TODO Auto-generated method stub
lst.removeViewAt(pos);
mylstadp.notifyDataSetChanged();
}
});
btnadd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
strname = edtname.getText().toString();
if(!TextUtils.isEmpty(strname)){
myary.add(strname);
}
mylstadp.notifyDataSetChanged();
/*mylstadp = new MyListAdapter(getApplicationContext(), myary);
lst.setAdapter(mylstadp);*/
}
});
}

}

then create MyInterface.java class for interface

package com.exampleinterfaceexample.act;

public interface MyInterface {
   public abstract void rowDeleted(Integer pos);
}

then create listview adapter MyListAdapter.java

package com.exampleinterfaceexample.act;


import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

public class MyListAdapter extends BaseAdapter {

Context mContext;
LayoutInflater layoutinflator;
ArrayList<String> araylistatende;
MyInterface myinterface;
public MyListAdapter(Context context, ArrayList<String> list) {
this.araylistatende = list;
this.mContext = context;
this.layoutinflator = LayoutInflater.from(context);
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return araylistatende.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return araylistatende.get(position);
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(final int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub

if (view == null) {
view = layoutinflator.inflate(R.layout.lstraw, null);
}
TextView txteventpasttype = (TextView) view.findViewById(R.id.textView1);
Button btn = (Button)view.findViewById(R.id.button1);
if(araylistatende.get(position) != null){
txteventpasttype.setText(araylistatende.get(position).toString());
}
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
araylistatende.remove(position);
notifyDataSetChanged();
}
});

return view;
}
// This is the interface method
public void setListeners(MyInterface  datasend)
{
myinterface = datasend;  
}
// This is the interface method
}

Now ,run the code.

This code is define the use of interface is android application.

Map V2 Example

create application and import google-play-services library.

create 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: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.diyamap.act.MainActivity" >

  <fragment 
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="fill_parent"
          android:name="com.google.android.gms.maps.SupportMapFragment"/>

</RelativeLayout>


and below is my menifest.xml file

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

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19"/>

    <permission
        android:name="com.diyamap.act.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- The following two permissions are not required to use
     Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="com.diyamap.act.permission.MAPS_RECEIVE" />

<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <uses-library android:name="com.google.android.maps"/>

        <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>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyDg11tWv7QEaQOFxzdD44O-C3ts11jxW_s" />
            </application>
</manifest>

here is MainActivity.java

package com.examplemap.act;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.StreetViewPanorama;
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.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {

GoogleMap map;
Drawable drawable;
Context mContext;
protected String latitude, longitude;
protected boolean gps_enabled, network_enabled;
// Double lat,lon;
MarkerOptions marker;
String lat,lon;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mContext = MainActivity.this;
Utility.registerLocationListener(mContext);
lat = Utility.getSharedKey("Latitude", mContext);
lon = Utility.getSharedKey("Longitude", mContext);
map.clear();

// Creating an instance of MarkerOptions
marker = new MarkerOptions();
LatLng latlng = new LatLng(Double.parseDouble(lat),
Double.parseDouble(lon));

marker = new MarkerOptions().position(latlng).title("Hello Maps").snippet("Population: 4,137,400");

// Draw  ground overlay 
/*GroundOverlayOptions newarkMap = new GroundOverlayOptions()
        .image(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
        .position(latlng, 8600f, 6500f);
map.addGroundOverlay(newarkMap);*/

// Custom Marker Icon

/*
* fromAsset(String assetName) – Loading from assets folder fromBitmap
* (Bitmap image) – Loading bitmap image fromFile (String path) –
* Loading from file fromResource (int resourceId) – Loading from
* drawable resource
*/
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

map.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(Double.parseDouble(lat), Double
.parseDouble(lon))).zoom(12).build();

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

// Changing Map Type
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// map.setMapType(GoogleMap.MAP_TYPE_NONE);

// Showing Current Location
map.setMyLocationEnabled(true); // false to disable

// Zooming Buttons
map.getUiSettings().setZoomControlsEnabled(true); // true to enable

// Zooming Functionality
map.getUiSettings().setZoomGesturesEnabled(true);

// Compass Functionality
map.getUiSettings().setCompassEnabled(true);

// My Location Button
map.getUiSettings().setMyLocationButtonEnabled(true);

// Map Rotate Gesture
map.getUiSettings().setRotateGesturesEnabled(true);
}
}

create Utility.java for common function define here

package com.examplemap.act;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

@SuppressLint("SimpleDateFormat")
public class Utility {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
return info != null;
}
public static void setSharedKey(String key, String value, Context context) {
SharedPreferences spre = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = spre.edit();
prefEditor.putString(key, value);
//prefEditor.clear();
prefEditor.commit();
}
public static String getSharedKey(String key, Context context) {
SharedPreferences spre = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
return spre.getString(key, "");
}
public static AlertDialog myAlertDialog;
  public static void showDialogwithTitle(Context context,String message) {

         AlertDialog.Builder builder = new AlertDialog.Builder(context);
         //builder.setTitle(context.getResources().getString(R.string.app_name));
         builder.setMessage(message);
         builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int arg1) {
                     dialog.dismiss();
                 }});
         builder.setCancelable(false);
         myAlertDialog = builder.create();
         myAlertDialog.show();
 }
  
  
public static void registerLocationListener(Context context) {
LocationManager lManager = null;
CurrentLocListener cListener = null;
lManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
cListener = new CurrentLocListener(context);
boolean isGpsEnabled = false;
boolean isNetworkEnabled = false;
isGpsEnabled = lManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = lManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGpsEnabled) {
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
cListener);
Location location = lManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Utility.setSharedKey("Latitude",
String.valueOf(location.getLatitude()), context);
Utility.setSharedKey("Longitude",
String.valueOf(location.getLongitude()), context);
}
}
if (isNetworkEnabled) {
lManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, cListener);
Location location = lManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Utility.setSharedKey("Latitude",
String.valueOf(location.getLatitude()), context);
Utility.setSharedKey("Longitude",
String.valueOf(location.getLongitude()), context);
}
}
}
}

then create CurrentLocListener.java

package com.examplemap.act;


import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;

public class CurrentLocListener implements LocationListener {
private static final String TAG = "CurrentLocListener - ";
public static final String ACTION_LOCATION_CHANGED = "tixe.act.ACTION_LOCATION_CHANGED";
Context mContext;
String latitude,longitude,token;
public CurrentLocListener(Context context){
Log.i(TAG, TAG + "CurrentLocListener - ");
mContext = context;
}

@Override
public void onLocationChanged(Location location) {
Log.i(TAG, TAG + "onLocationChanged - Latitude: " + String.valueOf(location.getLatitude()) + " Longitude: " + String.valueOf(location.getLongitude()));
Utility.setSharedKey("Latitude", String.valueOf(location.getLatitude()), mContext);
Utility.setSharedKey("Longitude", String.valueOf(location.getLongitude()), mContext);
Intent mIntent = new Intent(ACTION_LOCATION_CHANGED);
mContext.sendBroadcast(mIntent);
}

@Override
public void onProviderDisabled(String provider) {
Log.i(TAG, TAG + "onProviderDisabled - ");
}

@Override
public void onProviderEnabled(String provider) {
Log.i(TAG, TAG + "onProviderEnabled - ");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, TAG + "onStatusChanged - ");
}
}

Now,

for get API key go to https://console.developers.google.com ,and create project over there , then in that project go to APIs & auth tab and Enable google maps android v2 and go to next Credential tab and there create Public API access ,and click on Create new key , and click on Android key  here we need SHA1 key


For getting SHA1 key open terminal and write below command

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
password : android

it will create SHA1 key

use that key in api console project for create Androidkey

put there SHA1key;yourandroidapppackagename
and click on create button it creates API key for map.

your code is ready to run.



Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...