Saturday, December 21, 2013

How To Change Unix TimeStamp To Date,Days and Hours in Java and Android.

long timeInMilliseconds = 1388205000; 
long end=timeInMilliseconds*1000; 
long current = System.currentTimeMillis(); 
long diff = end - current ;
 int hrCount = (int) ((diff / (1000 * 60 * 60)) % 24); 
int dayCount = (int) diff / (24 * 60 * 60 * 1000);

Sunday, December 15, 2013

Crop image in circular shape in android.

Public Class Rounder{
           public Bitmap getRoundedShape(Bitmap scaleBitmapImage) { 
            int targetWidth = 125;
            int targetHeight = 125; 
           Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,            targetHeight,Bitmap.Config.ARGB_8888); 

         Canvas canvas = new Canvas(targetBitmap);  
         Path path = new Path(); 
         path.addCircle(((float) targetWidth - 1) / 2, ((float) targetHeight - 1) / 2, (Math.min(((float)     targetWidth), ((float) targetHeight)) / 2), Path.Direction.CCW); 
        canvas.clipPath(path); 
        Bitmap sourceBitmap = scaleBitmapImage; 
       canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),    sourceBitmap.getHeight()), new Rect(0, 0, targetWidth, targetHeight), null); 
 return targetBitmap; }

}

and use it as

Bitmap roundedBitmapImage=new Rounder().getRoundedShape(YourNormalBitmapImage);

Saturday, December 14, 2013

Simple Client Server Communication in android.



In this tutorial I’ll be assuming that you at least:
Have a basic knowledge of android
Have already developed a few small android application
I’ll be using the default HttpClient from org.apache.http package.

Client server communication is this much simple when it comes to android.
Create HttpClient with the default constructor.
Create a HttpGet or HttpPost object depending upon your needs, in this case I made a GET object so that we can know whats going on.
Initialize the object with a GET or POST url.
Execute the GET/POST object through the Http and you’ll get the server’s response in the response object of HttpResponse.



Get data from server.

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("YOUR URL");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Unable to complete your request", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
Toast.makeText(this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Caught IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Caught Exception", Toast.LENGTH_SHORT).show();
}

Monday, December 9, 2013

How To call HTTPS web services in android.

1.First You have to create a custom httpclient  in a class like:-

import java.security.KeyStore;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
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;



public class HttpsClient {
public static HttpClient 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();
}
}

}


2.Then creare a ssl factory class like:-

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");
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();
}
}

3. create a method ( trustAllHosts() )to valide your certificates like:-

public static void trustAllHosts() {
X509TrustManager easyTrustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // Oh, I am easy!
            }

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // Oh, I am easy!
            }

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

};
  // Create a trust manager that does not validate certificate chains
           TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager };
           // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }

}


4.in your activity ,send data to server using post request like:-

BasicNameValuePair _emailpair = new BasicNameValuePair("email", email);
            BasicNameValuePair _passwordpair = new BasicNameValuePair("password",password);
            List<NameValuePair> _namevalueList = new ArrayList<NameValuePair>();
            _namevalueList.add(_emailpair);
            _namevalueList.add(_passwordpair);
            String response=SendData(url_login,_namevalueList);
            Log.e("===RESPONSE====>","===RESPONSE====>"+response);

//here is the SendData MEthod
//everytime when you hit any request either it is get or post,you have to call trustAllHosts() method;

public String SendData(String url, List<NameValuePair> _namevalueList) {
String _Response = null;
trustAllHosts() ;
HttpClient _httpclient = HttpsClient.getNewHttpClient();
HttpPost _httppost = new HttpPost(url);
        try {
        _httppost.setEntity(new UrlEncodedFormEntity(_namevalueList, HTTP.UTF_8));
    HttpResponse _httpresponse = _httpclient.execute(_httppost);
    int _responsecode = _httpresponse.getStatusLine().getStatusCode();
    Log.i("--------------Responsecode----------", "." + _responsecode);
    if (_responsecode == 200) {
                    InputStream _inputstream = _httpresponse.getEntity().getContent();
                    BufferedReader r = new BufferedReader(new InputStreamReader(_inputstream));
                    StringBuilder total = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                            total.append(line);
                    }
                    _Response = total.toString();
                    } else {
                    _Response = "Error";
                    }
        } catch (Exception e) {
        e.printStackTrace();
        }
    return _Response;
}

///// get request syntax is:-

public void GetAll_Products_List(String url_get_all_products_list) {
trustAllHosts() ;
HttpClient _httpclient = HttpsClient.getNewHttpClient();
HttpGet _httpget = new HttpGet(url_get_all_products_list);
try {
HttpResponse _httpresponse = _httpclient.execute(_httpget);
int _responsecode = _httpresponse.getStatusLine().getStatusCode();
Log.i("--------------Responsecode----------", "." + _responsecode);
if (_responsecode == 200) {
InputStream _inputstream = _httpresponse.getEntity().getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(_inputstream));
StringBuilder total = new StringBuilder();
                 String line;
                 while ((line = r.readLine()) != null) {
                         total.append(line);
                 }
                 String G_P_L = total.toString();
                 System.out.println(G_P_L);
}
} catch (Exception e) {
e.printStackTrace();
}
}else{
System.out.println("error");
}
} catch (Exception e) {
e.printStackTrace();
}
}

f