Saturday, June 15, 2013

An useful CommonMethods like getLatitudeLongitudeFromAddress etc

An useful CommonMethods like getLatitudeLongitudeFromAddress etc

An useful CommonMethods like validateEmail, getAddressFromGeo ......
please use this class and call the methods where you want

ex: CommonMethods.validateEmail(abc@gmail.com);

public class CommonMethods {

public static boolean validateEmail(String email) {
final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
         "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
         "\\@" +
         "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
         "(" +
         "\\." +
         "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
         ")+"
     );
try {
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
   }
   catch( NullPointerException exception ) {
       return false;
   }
}

/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::  This function get address from geo location (latitude and longitude):*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    public static List<Address> getAddressFromGeo(Context context, Double latitude, Double longitude) {
    List<Address> address = null;
    try {
List<Address> addresses = new Geocoder(context, Locale.getDefault()).getFromLocation(latitude, longitude, 1);
address = addresses;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return address;
    }

public static double[] getGPS(Context context) {
    LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);

/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;

for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}

double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}

public static String getMonth(int month) {
   return new DateFormatSymbols().getMonths()[month-1];
}

/**
* returns the string, the first char uppercase
*
* @param target
* @return
*/
public final static String asUpperCaseFirstChar(final String target) {
   if ((target == null) || (target.length() == 0)) {
       return target;
   }
   return Character.toUpperCase(target.charAt(0))
           + (target.length() > 1 ? target.substring(1) : "");
}

public static String convertURL(String str) {
   String url = null;
   try{
   url = new String(str.trim().replace(" ", "%20").replace("&", "%26")
           .replace(",", "%2c").replace("(", "%28").replace(")", "%29")
           .replace("!", "%21").replace("=", "%3D").replace("<", "%3C")
           .replace(">", "%3E").replace("#", "%23").replace("$", "%24")
           .replace("'", "%27").replace("*", "%2A").replace("-", "%2D")
           .replace(".", "%2E").replace("/", "%2F").replace(":", "%3A")
           .replace(";", "%3B").replace("?", "%3F").replace("@", "%40")
           .replace("[", "%5B").replace("\\", "%5C").replace("]", "%5D")
           .replace("_", "%5F").replace("`", "%60").replace("{", "%7B")
           .replace("|", "%7C").replace("}", "%7D"));
   }catch(Exception e){
       e.printStackTrace();
   }
   return url;
}

public static Address getLatitudeLongitudeFromAddress(Context context, String addressval, String zipcode) {
Geocoder coder = new Geocoder(context);
List<Address> address;
Log.d("address",addressval );
try {
if(!zipcode.equals("") && !zipcode.equals("null") && !zipcode.equals(null)) {
address = coder.getFromLocationName(zipcode, 5);
} else {
address = coder.getFromLocationName(addressval,5);
System.out.println("address" + address.get(0) );
}
   if (address != null && !address.isEmpty()) {
   Address location = address.get(0);
   location.getLatitude();
   location.getLongitude();
   return location;
   } else
    return null;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}

public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);


        // RECREATE THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
        return resizedBitmap;
    }

public static Bitmap ShrinkBitmap(String file, int width, int height){  
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bitmap   = BitmapFactory.decodeFile(file, bmpFactoryOptions);
       
        int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
        int widthRatio  = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
       
        if (heightRatio > 1 || widthRatio > 1){
           if (heightRatio > widthRatio){
            bmpFactoryOptions.inSampleSize = heightRatio;
           }else {
         bmpFactoryOptions.inSampleSize = widthRatio;
           }
        }        
        bmpFactoryOptions.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
        return bitmap;
    }

public static String getPath(Uri uri, Activity activity) {
   String[] projection = { MediaStore.Images.Media.DATA };
   Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
   int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
   cursor.moveToFirst();
   return cursor.getString(column_index);
}

/**
* Gets the last image id from the media store
* @return
*/
public static String getLastImageId(Activity activity) {
   final String[] imageColumns = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
   final String imageOrderBy = MediaStore.Images.Media._ID+" DESC";
   Cursor imageCursor = activity.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
   if(imageCursor.moveToFirst()){
       int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
       String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
       Log.d("Camera", "getLastImageId::id " + id);
       Log.d("Camera", "getLastImageId::path " + fullPath);
       imageCursor.close();
       return fullPath;
   } else {
       return "";
   }
}

public static String getFileExtension(String url) {
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension = "";
if (dotIndex == -1)
{
 filenameWithoutExtension = url.substring(slashIndex + 1);
}
else
{
 filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
return filenameWithoutExtension;
}

public static boolean checkImageExtension(String extension) {
String[] exten = {"bmp", "dds", "dng", "gif", "jpg", "png", "psd", "pspimage", "tga", "thm", "jpeg", "yuv"};
for (String val : exten) {
   if (extension.toLowerCase().contains(val)) {
    return true;
   }
}
return false;
}

public static boolean checkFileExtension(String extension) {
String[] exten = {"doc", "docx", "log", "msg", "odt", "pages", "rtf", "tex", "txt", "wpd", "wps"};
for (String val : exten) {
   if (extension.toLowerCase().contains(val)) {
    return true;
   }
}
return false;
}

//CommonMethods
public static double distance(double lat1, double lon1, double lat2, double lon2) {
     double theta = lon1 - lon2;
     double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
     dist = Math.acos(dist);
     dist = rad2deg(dist);
     dist = dist * 60 * 1.1515;
     return (dist);
}

public static double distFrom(double lat1, double lng1, double lat2,
double lng2) {
double earthRadius = 6371;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;

//Log.d("dist: " , ""+ dist + "--" + lat1 +"," + lng1 +  "--" + lat2 +"," + lng2 );
return (dist);

}

public static float metresToMiles(float metres) {

return (float) (metres * 0.000621371192);
}

public static float metresToKm(float metres) {

return (float) (metres * 0.001);
}

public static float Round(float Rval, int Rpl) {
float p = (float) Math.pow(10, Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float) tmp / p;
}
public static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
    }
public static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
    }

public static JSONObject getLocationInfo(String address) {

HttpGet httpGet = new HttpGet("http://maps.google."
+ "com/maps/api/geocode/json?address=" + address
+ "ka&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();

try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}

JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}

return jsonObject;
}

public static GeoPoint getGeoPoint(JSONObject jsonObject) {
double lon = 0.0;
Double lat = 0.0;
try {
lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
} catch (JSONException e) {
e.printStackTrace();
}

return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));

}


}

Android replace FRENCH characters to English characters

Android replace FRENCH characters to English characters
String french = "Tapez les mots français ici ............";
String english =slugify(french);

public  String slugify(String name) {
String[] hel=name.split("(?!^)");

for(int i=0;i<hel.length;i++){
if(hel[i].contains("é")||hel[i].contains("è")||hel[i].contains("à")||hel[i].contains("ù")||hel[i].contains("â")
||hel[i].contains("ê")||hel[i].contains("î")||hel[i].contains("ô")||hel[i].contains("û")||hel[i].contains("ë")
||hel[i].contains("ï")||hel[i].contains("ç")||hel[i].contains("æ")||hel[i].contains("œ")||hel[i].contains("ü")
||hel[i].contains("À")||hel[i].contains("Â")||hel[i].contains("Æ")||hel[i].contains("Ç")
||hel[i].contains("È")||hel[i].contains("É")||hel[i].contains("Ê")||hel[i].contains("Ë")||hel[i].contains("Î")
||hel[i].contains("Ï")||hel[i].contains("Ô")||hel[i].contains("Œ")||hel[i].contains("Ù")||hel[i].contains("Û")||hel[i].contains("Ü")){
name=name.replace("é", "e");
name=name.replace("è", "e");
name=name.replace("à", "a");
name=name.replace("ù", "u");
name=name.replace("â", "a");
name=name.replace("ê", "e");
name=name.replace("î", "i");
name=name.replace("ô", "o");
name=name.replace("û", "u");
name=name.replace("ë", "e");
name=name.replace("ï", "i");
name=name.replace("ç", "c");
name=name.replace("æ", "ae");
name=name.replace("œ", "oe");
name=name.replace("ü", "u");

name=name.replace("À", "A");
name=name.replace("Â", "A");
name=name.replace("Æ", "AE");
name=name.replace("Ç", "C");
name=name.replace("È", "E");
name=name.replace("É", "E");
name=name.replace("Ê", "E");
name=name.replace("Ë", "E");
name=name.replace("Î", "I");
name=name.replace("Ï", "I");
name=name.replace("Ô", "O");
name=name.replace("Œ", "OE");
name=name.replace("Ù", "U");
name=name.replace("Û", "U");
name=name.replace("Ü", "U");
}
}


String subjectString = "öäü";
        subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
        String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
        System.out.println(resultString);
       
        String s = "Papier, produit de pâte à papier, non précisé";
        String r = s.replaceAll("\\P{InBasic_Latin}", "");
        System.out.println("-----------"+r);