Friday, 14 November 2014

Sorting List in Ascending and Descending Order


sort_list.xml file

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

  <Button
        android:id="@+id/desc_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="48dp"
        android:layout_toRightOf="@+id/asc_button"
        android:text="DESC" />

    <ListView
        android:id="@+id/name_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/desc_button" >
    </ListView>

    <Button
        android:id="@+id/asc_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/name_list"
        android:layout_marginLeft="54dp"
        android:text="ASC" />


</RelativeLayout>

create sort_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
        <TextView
        android:id="@+id/name_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


</LinearLayout>


Then below is MainActivity.java

package com.examplemediaplayer.act;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity  implements OnClickListener {

private Button mAscButton;
    private Button mDescButton;
    private ListView mNameListView;
   
    private List<String> stringList;
    private StringAdapter stringAdapter;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sort_list);
       
        mAscButton = (Button) findViewById(R.id.asc_button);
        mDescButton = (Button) findViewById(R.id.desc_button);
        mNameListView = (ListView) findViewById(R.id.name_list);
       
        stringList = new ArrayList<String>();
        stringList.add("Android");
        stringList.add("Iphone");
        stringList.add("ipad");
        stringList.add("Windows");
        stringList.add("Blackberry");
        
        stringAdapter = new StringAdapter(MainActivity.this, R.layout.sort_list_item, stringList);
        mNameListView.setAdapter(stringAdapter);
       
        mAscButton.setOnClickListener(this);
        mDescButton.setOnClickListener(this);
       
       
    }
    // Comparator for Ascending Order
    public static Comparator<String> StringAscComparator = new Comparator<String>() {

        public int compare(String app1, String app2) {

            String stringName1 = app1;
            String stringName2 = app2;
           
            return stringName1.compareToIgnoreCase(stringName2);
        }
    };

    //Comparator for Descending Order
    public static Comparator<String> StringDescComparator = new Comparator<String>() {

        public int compare(String app1, String app2) {

            String stringName1 = app1;
            String stringName2 = app2;
           
            return stringName2.compareToIgnoreCase(stringName1);
        }
    };
   // Your Own Custom Adapter
    private class StringAdapter extends ArrayAdapter<String> {
        // Attributes
        private List<String> strModel;

        public StringAdapter(Context context, int textViewResourceId,
                List<String> strModel) {
            super(context, textViewResourceId, strModel);
            this.strModel = strModel;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            Holder holder = null;

            if (view == null) {
                view = View.inflate(MainActivity.this,
                        R.layout.sort_list_item, null);

                holder = new Holder();
                holder.StringNameTextView = (TextView) view
                        .findViewById(R.id.name_text_view);

                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            String nameText=strModel.get(position);
            holder.StringNameTextView.setText(nameText);
            return view;
        }
    }
   
    static class Holder
    {
        private TextView StringNameTextView;
    }

    @Override
    public void onClick(View v) {

        switch(v.getId()) {
        case R.id.asc_button :
            Collections.sort(stringList, StringAscComparator);
            Toast.makeText(MainActivity.this, "Sorting in Ascending Order", Toast.LENGTH_LONG).show();
            break;
        case R.id.desc_button :
            Collections.sort(stringList, StringDescComparator);
            Toast.makeText(MainActivity.this, "Sorting in Descending Order", Toast.LENGTH_LONG).show();
            break;
        }
        stringAdapter.notifyDataSetChanged();
       
    }
}

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.

Snackbar in Kotlin

How to show snackbar in place of toast message , below is the code for showing snackbar in kotlin. Below code is put in Utils.kt  (common fi...