Friday, January 10, 2014

Resizeable ImageView in android:

package com.yourpackage;
 import android.content.Context;
 import android.graphics.drawable.Drawable; 
import android.util.AttributeSet; 
import android.widget.ImageView; 


 public class ResizableImageView extends ImageView { 
          public ResizableImageView(Context context, AttributeSet attrs) {
          super(context, attrs); 
 }
 public ResizableImageView(Context context) {
      super(context); 
 } 
 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
                   Drawable d = getDrawable(); if (d == null) {                           super.setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); 
                  return; 
 } 
 int imageHeight = d.getIntrinsicHeight(); 
 int imageWidth = d.getIntrinsicWidth(); 
 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 
 float imageRatio = 0.0F; 
 if (imageHeight > 0) { 
 imageRatio = imageWidth / imageHeight; 
 } 
 float sizeRatio = 0.0F; 
 if (heightSize > 0) { 
 sizeRatio = widthSize / heightSize;
 } 
 int width; int height; 
 if (imageRatio >= sizeRatio) { 
 // set width to maximum allowed width = widthSize; 
 // scale height height = width * imageHeight / imageWidth; 
 } else {
 // set height to maximum allowed height = heightSize; 
 // scale width width = height * imageWidth / imageHeight; 
 }
 setMeasuredDimension(width, height);
 }
 }

THIS IS THE IMAGEVIEW:
`< com.YOURPACKAGENAME.ResizableImageView 
android:id="@+id/imagetweet" 
android:layout_width="match_parent" 
android:layout_height="160dp"
 android:layout_alignParentLeft="true"
 android:layout_alignParentTop="true" 
android:adjustViewBounds="true"
 android:scaleType="centerCrop" />

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

Wednesday, November 6, 2013

Difference between px, dp, dip and sp in Android.

px is one pixel. scale-independent pixels ( sp ) and density-independent pixels ( dip ) you want to use sp for font sizes and dip for everything else.dip==dp

px
Pixels - corresponds to actual pixels on the screen.
in
Inches - based on the physical size of the screen.
mm
Millimeters - based on the physical size of the screen.
pt
Points - 1/72 of an inch based on the physical size of the screen.
dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".
sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.
How To Change Text Color And Back Ground Color Of Action Bar In Android.

Text Color:-
according to my knowledge,the id of Action Bar Title id hidden,first you have to get id of that Acton Bar Title like:-

int ActionBarTitleID = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
 now use settext on this ID like 
TextView yourTextView = (TextView)findViewById(ActionBarTitleID); yourTextView.setTextColor(colorId);



If you use 
Sherlock Actionbar you may use the sherlock-actionbar-id for supported actionbars (Android below 3.0)

int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android"); 
if ( 0 == titleId ) titleId = com.actionbarsherlock.R.id.abs__action_bar_title;



Back Ground Color:-

mActionBar.setBackgroundDrawable(new ColorDrawable(0xff00DDED)); mActionBar.setDisplayShowTitleEnabled(false);

 mActionBar.setDisplayShowTitleEnabled(true);

Saturday, November 2, 2013

How To Send Email In Android Or Java With Proxy Server.



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EMailSender {
public EMailSender(String host, final String from, final String pass, String to, String sub, String mess) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
Authenticator auth = new Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}};
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(sub);
message.setText(mess);
Transport.send(message);
}

public static void main(String arg[]) throws Exception {
if(arg.length == 5) {
StringBuilder message = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp = "", subject;
System.out.print("Enter subject: ");
subject = br.readLine();
System.out.println("Enter the message (end it with a . on a single line):");
while((temp = br.readLine()) != null) {
if(temp.equals("."))
break;
message.append(temp+"\n");
}
System.out.println("Sending message...");
new EMailSender(arg[0], arg[1], arg[2], arg[3], subject, message.toString());
System.out.println("Sent the message.");
}
else System.err.println("Usage:\njava SendTextMail <host> <port> <from> <pass> <to>");
}
}


Call Constructor Of This Class In Your Activity On Button Click.

Thursday, October 31, 2013

Difference between Handler and AsyncTask in Android.

Handler and AsyncTasks are way to implement multithreading in android with UI/Event Thread. Handler is available since Android API level 1 & AsyncTask is available since API level 3.


Android Handler
Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.
The Handler is associated with the application’s main thread. It handles and schedules messages and runnables sent from background threads to the app main thread.
If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.
There are two main uses for a Handler. First is to schedule messages and runnables to be executed as some point in the future; and second Is to enqueue an action to be performed on a different thread than your own.
Scheduling messages is accomplished with the the methods like post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods.
When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create.
You can create your own threads, and communicate back with the main application thread through a Handler.



Android AsynkTask

Async task enables you to implement MultiThreading without get Hands dirty into threads. AsyncTask enables proper and easy use of the UI thread. It allows performing background operations and passing the results on the UI thread.
If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
In onPreExecute you can define code, which need to be executed before background processing starts.
doInBackground have code which needs to be executed in background, here in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply.
onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread
onPostExecute() method handles results returned by doInBackground method.
The generic types used are
Params, the type of the parameters sent to the task upon execution
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
If an async task not using any types, then it can be marked as Void type.
An running async task can be cancelled by calling cancel(boolean) method.