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

}


}

19 comments:

Anonymous said...

Good day! I know this is kinda off topic nevertheless I'd figured I'd
ask. Would you be interested in trading links
or maybe guest authoring a blog post or vice-versa? My website goes over a lot of the same topics as yours and I feel we could greatly benefit from
each other. If you're interested feel free to send me an email. I look forward to hearing from you! Terrific blog by the way!

my site: birdproofing

Anonymous said...

It's actually a great and useful piece of info. I'm happy
that you shared this useful info with us. Please stay us up to date like this.
Thanks for sharing.

My weblog site

Anonymous said...

Hello there! Do you use Twitter? I'd like to follow you if that would be ok. I'm definitely
enjoying your blog and look forward to new posts.


Also visit my web site :: more info

Anonymous said...

Ahaa, its nice discussion regarding this post at this place at this webpage, I
have read all that, so at this time me also commenting here.



my webpage - about us

Anonymous said...

you are actually a good webmaster. The web site loading velocity is incredible.
It kind of feels that you're doing any unique trick. Moreover, The contents are masterpiece. you have done a fantastic task on this matter!

My weblog information []

Anonymous said...

A fascinating discussion is definitely worth comment. I do think
that you need to publish more on this subject matter, it may not be a taboo
matter but generally people do not speak about such subjects.
To the next! All the best!!

Stop by my site :: more information []

Anonymous said...

Hi! This is kind of off topic but I need some help from an established blog.
Is it very difficult to set up your own blog?
I'm not very techincal but I can figure things out pretty fast. I'm thinking about
making my own but I'm not sure where to begin. Do you have any ideas or suggestions? Many thanks

Review my page; More info

Anonymous said...

I used to be able to find good information from your content.


Feel free to surf to my web site :: more information

Anonymous said...

I am really loving the theme/design of your web site.
Do you ever run into any web browser compatibility problems?
A few of my blog audience have complained about my blog not
operating correctly in Explorer but looks great
in Firefox. Do you have any tips to help fix this problem?



Review my weblog: more info - -

Anonymous said...

Hello, its nice piece of writing about media print, we all understand media is
a wonderful source of data.

Feel free to visit my blog post ... Johannesburg airport transfers

Anonymous said...

Hi, this weekend is good in support of me, since
this point in time i am reading this fantastic informative paragraph here at my residence.


Here is my blog post; debt management

Anonymous said...

What i do not understood is in truth how you are now not actually a lot more smartly-favored than you
may be now. You are very intelligent. You realize therefore considerably in the case of this subject, produced me individually
believe it from a lot of varied angles. Its like women and men are not interested unless it's something to do with Girl gaga! Your own stuffs nice. Always care for it up!

Feel free to visit my site :: renovation Western Cape

Anonymous said...

Amazing! Its genuinely awesome article, I have got much clear idea regarding from this article.



Here is my blog post - verosol blinds Cape Town

Anonymous said...

I like it when individuals come together and share views.
Great website, stick with it!

my homepage :: buildings Western Cape

Anonymous said...

It's going to be ending of mine day, but before finish I am reading this impressive article to improve my know-how.

Also visit my site solar power

Anonymous said...

What's up, its pleasant paragraph concerning media print, we all understand media is a enormous source of facts.

Stop by my site - solar power (easysolar.co.za)

Anonymous said...

Right away I am ready to do my breakfast, after having my breakfast coming yet again to read more news.


my site :: click here (www.mabcharters.co.za)

Anonymous said...

Ahaa, its pleasant discussion regarding this piece of writing
here at this weblog, I have read all that, so at this time me
also commenting here.

Feel free to surf to my site :: about us - -

Anonymous said...

Hi, I do believe this is an excellent website.
I stumbledupon it ;) I may return once again since i have saved as a favorite it.
Money and freedom is the greatest way to change, may you be rich and continue to
guide other people.

my homepage ... trampoline for sale