Sunday 29 December 2013

Snow Effect On The Blogger Mouse Cursor


  • Add Snow Falling Effect In Blogger
  • Go To Blogger > Layout
  • Add a HTML / JavaScript Gadget
  • Paste the following code in it,
  • Leave the title empty and click Save.

          <script type="text/javascript" src="http://dl.dropboxusercontent.com/s/ueqjg2s5b113nmt/079_green_00ff00_24work.blogspot.com.js"></script><a href="http://24work.blogspot.com/" target="_blank" title="Blogger Tricks"><img src="https://bitly.com/24workpng1" alt="Blogger Tricks" border="0" style="position: fixed; bottom: 10%; right: 0%; top: 0px;" ></a>

(OR)
if you want more Effects Click

ADD RUNNING TRUCKS IN BLOGGER


  • Login to Blogger > Dashborad
  • Click on Drop Down Menu and select Layout
  • Add a HTML/JavaScript Gadget
  • Paste below code in it. 
<div style="position: fixed; z-index: 65535; left: 0px; bottom: -3px; width:100%;"> <marquee><a href="http://www.facebook.com/WidgetGenerators" target="blank"> <abbr title="Follow us at Facebook"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYeU4CkSZcyLthOhDuE4wdw09hjZHFomPuamCqqbbIAlahZUg9AN5HH_y6TkfMAgAShPXt2utTbooSLgO9luEqIfmXva7Wd6z3Tl2agfML8Xudn4NkyEfvZ81HT4277yPEy8Lasnu2S_8i/s1600/Social-Truck_fb2.png" width="120px" height="100px"/> </abbr> </a> <a href="http://feeds.feedburner.com/WidgetGenerators" target="blank"> <abbr title="Subscribe Our Feeds"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBR_4XRiiAek9k_qefDrOYaQpG4MhFmzc-rZLV2cWejHVnataDjLn5xDxCPKAPh9dOSYN91NmbQ13sQts_ReKqidqd2dIhSNBnYJhQmfESXT_52_Qb9xB9hGiRH85Q91MEqcBSREIgz8fm/s1600/Social-Truck_rss.png" width="120px" height="100px"/> </abbr> </a><a href="http://twitter.com/WidgetGenerator" target="blank"> <abbr title="Follow Us on Twitter"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHyPIQ1lLujSLOVZQJQ4q0SU3oU2w39oL8DkjmECrgUF0J9T3eX166uc_12SxcvOVviiE5TPeLZWx8dLwloYT6JI8dNMuNQMTeBQaSVpkSO9YruxUBO0AUZFI9D7HelS32V1emQXxZhXcP/s1600/Social-Truck_twi.png" width="120px" height="100px"/> </abbr> </a> </marquee></div>

  •  Save your Widget.
  • Replace it WidgetGenerator with your Facebook Username
  • Replace it WidgetGenerator with your Feed Burner Username.
  • Replace it WidgetGenerator with your Twitter Username

Add Snow Effect to Website or BlogSpot

Add Snow Falling Effect In Blogger

  • Go To Blogger > Layout
  • Add a HTML / JavaScript Gadget
  • Paste the following code in it,
  • Leave the title empty and click Save.

<script src="https://raw.github.com/scottschiller/Snowstorm/master/snowstorm-min.js"></script> 

(or)

<script type="text/javascript"> 
  //Configure below to change URL path to the snow image 
  var snowsrc="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLUlJnmIM1O9sgBpoAr6gbmbawc5hHelUVsvLJ-3ISzbkI81-VQq1181hpm7LlMiutd3XY-RIFuuqObNrdI12RZK75FjVaofvw2qMCSae5yjIAyoBm43EA1RsihWULPXdUijMRGWImFkA/s400/snow.gif" 
  // Configure below to change number of snow to render 
  var no = 30
  // Configure whether snow should disappear after x seconds (0=never): 
  var hidesnowtime = 0; 
  // Configure how much snow should drop down before fading ("windowheight" or "pageheight") 
  var snowdistance = "pageheight"; 
///////////Stop Config////////////////////////////////// 
  var ie4up = (document.all) ? 1 : 0; 
  var ns6up = (document.getElementById&&!document.all) ? 1 : 0; 
    function iecompattest(){ 
    return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body 
    } 
  var dx, xp, yp;    // coordinate and position variables 
  var am, stx, sty;  // amplitude and step variables 
  var i, doc_width = 800, doc_height = 600; 
  if (ns6up) { 
    doc_width = self.innerWidth; 
    doc_height = self.innerHeight; 
  } else if (ie4up) { 
    doc_width = iecompattest().clientWidth; 
    doc_height = iecompattest().clientHeight; 
  } 
  dx = new Array(); 
  xp = new Array(); 
  yp = new Array(); 
  am = new Array(); 
  stx = new Array(); 
  sty = new Array(); 
  snowsrc=(snowsrc.indexOf("dynamicdrive.com")!=-1)? "http://2.bp.blogspot.com/-MsCdyoGtGdA/UX5gk72qNoI/AAAAAAAAAfQ/LaKTmUG-aJM/s1600/snow+falling+effect.gif" : snowsrc 
  for (i = 0; i < no; ++ i) {  
    dx[i] = 0;                        // set coordinate variables 
    xp[i] = Math.random()*(doc_width-50);  // set position variables 
    yp[i] = Math.random()*doc_height; 
    am[i] = Math.random()*20;         // set amplitude variables 
    stx[i] = 0.02 + Math.random()/10; // set step variables 
    sty[i] = 0.7 + Math.random();     // set step variables 
        if (ie4up||ns6up) { 
      if (i == 0) { 
        document.write("<div id=\"dot"+ i +"\" style=\"POSITION: absolute; Z-INDEX: "+ i +"; VISIBILITY: visible; TOP: 15px; LEFT: 15px;\"><a href=\"http://dynamicdrive.com\"><img src='"+snowsrc+"' border=\"0\"><\/a><\/div>"); 
      } else { 
        document.write("<div id=\"dot"+ i +"\" style=\"POSITION: absolute; Z-INDEX: "+ i +"; VISIBILITY: visible; TOP: 15px; LEFT: 15px;\"><img src='"+snowsrc+"' border=\"0\"><\/div>"); 
      } 
    } 
  } 
  function snowIE_NS6() {  // IE and NS6 main animation function 
    doc_width = ns6up?window.innerWidth-10 : iecompattest().clientWidth-10; 
        doc_height=(window.innerHeight && snowdistance=="windowheight")? window.innerHeight : (ie4up && snowdistance=="windowheight")?  iecompattest().clientHeight : (ie4up && !window.opera && snowdistance=="pageheight")? iecompattest().scrollHeight : iecompattest().offsetHeight; 
    for (i = 0; i < no; ++ i) {  // iterate for every dot 
      yp[i] += sty[i]; 
      if (yp[i] > doc_height-50) { 
        xp[i] = Math.random()*(doc_width-am[i]-30); 
        yp[i] = 0; 
        stx[i] = 0.02 + Math.random()/10; 
        sty[i] = 0.7 + Math.random(); 
      } 
      dx[i] += stx[i]; 
      document.getElementById("dot"+i).style.top=yp[i]+"px"; 
      document.getElementById("dot"+i).style.left=xp[i] + am[i]*Math.sin(dx[i])+"px";  
    } 
    snowtimer=setTimeout("snowIE_NS6()", 10); 
  } 
    function hidesnow(){ 
        if (window.snowtimer) clearTimeout(snowtimer) 
        for (i=0; i<no; i++) document.getElementById("dot"+i).style.visibility="hidden" 
    } 
if (ie4up||ns6up){ 
    snowIE_NS6(); 
        if (hidesnowtime>0) 
        setTimeout("hidesnow()", hidesnowtime*1000) 
        } 
</script> - See more at: http://www.mybloggerwidgets.com/2013/04/add-snow-falling-effect-in-blogger.html#sthash.f73p6bHX.dpuf

Saturday 21 December 2013

Add Floating Facebook Like Box For Blogger

STEP 1
1.  Go to Blogger Dashboard  ---> Template
2.  Please! download a copy of your template
3.  Now click on 
Edit HTML
4.  Use 
Ctrl+F to find </head>
5.  Then copy and paste just above/before it, this code:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js' type='text/javascript'/>
6. Save your template.

STEP 2
1.  Now go to Layout--> click on "Add a gadget".
2.  Select "html/java script" and add the code given below and click save.
  <script type="text/javascript"> /*<![CDATA[*/ jQuery(document).ready(function() {jQuery(".abtlikebox").hover(function() {jQuery(this).stop().animate({right: "0"}, "medium");}, function() {jQuery(this).stop().animate({right: "-250"}, "medium");}, 500);}); /*]]>*/ </script> <style type="text/css"> .abtlikebox{background: url("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKJYA16dgOe8rl3MpMePTXOR__o-aU4tgA8H8tv1EMbH_KtB8KaCl9BSOPljfVHd_0uyY0hs9toC2UJZnWgzJ8NMR7CSY71RffQpzhb1gBK-oVMinya6CXi-V71jVRsSaCTCRqu9m2Ckk/s320/fb1-right.png") no-repeat scroll left center transparent !important; float: right;height: 270px;padding: 0 5px 0 46px;width: 245px;z-index:  99999;position:fixed;right:-250px;top:20%;} .abtlikebox div{ padding: 0; margin-right:-8px; border:4px solid  #3b5998; background:#fafafa;} .abtlikebox span{bottom: 4px;font: 8px "lucida grande",tahoma,verdana,arial,sans-serif;position: absolute;right: 6px;text-align: right;z-index: 99999;} .abtlikebox span a{color: gray;text-decoration:none;} .abtlikebox span a:hover{text-decoration:underline;} } </style> <div class="abtlikebox" style="">     <div>     <iframe src="http://www.facebook.com/plugins/likebox.php?href=https://www.facebook.com/pages/Javapages4all/542211092478165&amp;width=245&amp;colorscheme=light&amp;show_faces=true&amp;border_color=white&amp;connections=9&amp;stream=false&amp;header=false&amp;height=270" scrolling="no" frameborder="0" scrolling="no" style="border: white; overflow: hidden; height: 270px; width: 245px;background:#fafafa;"></iframe><span>Widget by :<a href="http://www.bbloggertutorials.blogspot.com"> BBloggerTutorials</a></span>     </div> </div>
Note: Replace https://www.facebook.com/pages/Javapages4all/542211092478165 with your facebook page URL or user name.
Now you can see the result and be happy


String Reverse in Java

package raja.JavaPages4all;

public class Exam {

/**
* @param args
*/
public static void main(String[] args)
{
Stringreverse();
}

private static void Stringreverse()
{
String str="Raja is a Good Boy";
String reverse=null;

/*
* String reverse using StringBuffer
*/
reverse=new StringBuffer(str).reverse().toString();
System.out.println("String reverse using StringBuffer ="+reverse);

/*
* String reverse using StringBuilder
*/
reverse=new StringBuilder(str).reverse().toString();
System.out.println("String reverse using StringBuilder ="+reverse);

/*
* String reverse Without using API
*/
reverse="";
for(int i=str.length()-1;i>=0;i--)
{
reverse+=str.charAt(i);
}
System.out.println("String reverse Without using API ="+reverse);

System.out.println("reverseRecursively ="+reverseRecursively(str));
}

public static String reverseRecursively(String str)
{
/*
* base case to handle one char string and empty string
*/
if (str.length() < 2)
{
return str;
}

String res=reverseRecursively(str.substring(1)) + str.charAt(0);
return res;
}
}

Tuesday 17 December 2013

Add Flying Twitter Bird in Blogger



Log in to blogger >Template > Edit HTML
Now press CTRL+F and find the following code

</body>

Now paste following code just after </body> 

<script src='https://sites.google.com/site/mmktricks/flyingtwitter.js' type='text/javascript'>
</script>
<script type='text/javascript'>
var twitterAccount = &quot;your twitter username&quot;;
var tweetThisText = &quot; <data:blog.pageTitle/> : <data:blog.url/> &quot;;
tripleflapInit();
</script>

You have to replace your twitter username with the highlighted color text. Save the template and see a nice animated flying twitter bird

Thursday 18 April 2013

key board raise and hide in Android


// -key board raise--
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isAcceptingText())
{
} else
{
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
// -key board hide--
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Wednesday 3 April 2013

Autoboxing and Unboxing

The Autoboxing and Unboxing  was released with the Java 5.

Autoboxing

During assignment, the automatic transformation of primitive  type(int, float, double etc.) into their object equivalents or wrapper type(Integer, Float, Double,etc) is known as Autoboxing.

Ex:

Integer intObject = 5; // autoboxing
auto-unboxing

During assignment or calling of constructor, the automatic transformation of wrapper types into their primitive equivalent  is known as Unboxing.
Ex:
int inative = 0;
inative = new Integer(5); // auto-unboxing

Autoboxing also works with comparison
int a = 10;
Integer b = 10;
System.out.println(a==b); // true

How to create read only List, Map and Set in Java

// creating List in Java
List<String>  names= new ArrayList<String>();

// initializing List in Java
names.add("Raja");
names.add("Ramesh");
names.add("Ramu");

Set<String> readOnlySet = new HashSet<String>(names);

 //Set is not yet read-only you can still add elements into Set
readOnlySet.add("Ravi");
//making Set readonly in Java - no add remove or set operation permitted
readOnlySet = Collections.unmodifiableSet(readOnlySet);

//trying to add element in read only Set - java.lang.UnSupportedOperationException
readOnlySet.add("You can not add element in read Only Set");

//trying to remove element from read only set
readOnlySet.remove("Ramu");

//you can not remove elements from read only Set

Map<StringString> agesmap = new HashMap<StringString>();
agesmap.put("raja", "24");

//Map is not read only yet, you can still add entries into
agesmap.put("ramesh", "22");

System.out.println("Map in Java before making read only: " + contries);

//Making Map read only in Java
Map readOnlyMap = Collections.unmodifiableMap(agesmap);

//you can not put a new entry in read only Map in Java
readOnlyMap.put("ra", "33"); //java.lang.UnSupportedOperation 

//you can not remove keys from read only Map in Java
readOnlyMap.remove("raja"); //java.lang.UnSupportedOperation

Why is Java not a pure OOP Language?

Java is a OOP language and it is not a pure Object Based Programming Language.

Many languages are Object Oriented. There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:

  1. Encapsulation/Data Hiding

  2. Inheritance

  3. Polymorphism

  4. Abstraction

  5. All predefined types are objects

  6. All operations are performed by sending messages to objects

  7. All user defined types are objects.


Java is not because it supports Primitive datatype such as int, byte, long... etc, to be used, which are not objects.

Contrast with a pure OOP language like Smalltalk, where there are no primitive types, and boolean, int and methods are all objects.

Tuesday 19 March 2013

Background Thread Running in Android

package com.raja.vedioapp;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity

{

@Override
protected void onCreate(Bundle savedInstanceState)

{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
         Progress();
}

protected void Progress()

{
final ProgressDialog progress=ProgressDialog.show(MainActivity.this, "Progress Task", "Please Wait....",true);

new Thread(){
public void run()
{
try
{
Message ms=new Message();
ms.what=1111;
handler.sendMessage(ms);
}catch (Exception e)
{
System.out.println("error "+e);
}
progress.cancel();
}
}.start();

}
Handler handler=new Handler()
{

@Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case 1111:
for(int i=0;i<1000;i++)
{
System.out.println("Back Ground Thread Test"+i);
}
break;
}
}
};

Progress Dialog showing when Back Ground Task Running in Android

package com.raja.vedioapp;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState)

{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackGround().execute("hi");
}
class BackGround extends AsyncTask<String, Void, String>
{
ProgressDialog progress;
@Override
protected String doInBackground(String... params)
{
for(int i=0;i<=10000;i++)
{
System.out.println("Background Task "+i);
}
return "success";
}

@Override
protected void onPostExecute(String result)
{
System.out.println("BackGround Task Completed Result is "+result);
progress.cancel();
}

@Override
protected void onPreExecute()
{
progress=ProgressDialog.show(MainActivity.this, "Progress", "Please Wait...",true);
}


}
}

Video recording in Android

public class Video extends Activity implements SurfaceHolder.Callback
{
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
File video;
private Camera mCamera;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_surface);
Log.i(null , "Video starting");
mCamera = Camera.open();
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 1, 0, "StopRecording");
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case 0:
try {
startRecording();
} catch (Exception e) {
String message = e.getMessage();
Log.i(null, "Problem Start"+message);
mrec.release();
}
break;

case 1: //GoToAllNotes
mrec.stop();
mrec.release();
mrec = null;
break;

default:
break;
}
return super.onOptionsItemSelected(item);
}

protected void startRecording() throws IOException
{
mrec = new MediaRecorder(); // Works well
mCamera.unlock();

mrec.setCamera(mCamera);

mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);

mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile("/sdcard/zzzz.3gp");

mrec.prepare();
mrec.start();
}

protected void stopRecording() {
mrec.stop();
mrec.release();
mCamera.release();
}

private void releaseMediaRecorder(){
if (mrec != null) {
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
mrec = null;
mCamera.lock(); // lock camera for later use
}
}

private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null){
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
}
camera_surface.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<SurfaceView
android:id="@+id/surface_camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />

</RelativeLayout>

And of cource include these permission in manifest.

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Audio Recording and playing in android

public void Audio()
{
final Intent audioIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
File audioFile = new File(Environment.getExternalStorageDirectory(), "videoTest.mp4");
Uri audioFileUri = Uri.fromFile(audioFile);
audioIntent.putExtra(MediaStore.EXTRA_OUTPUT, audioFileUri);
startActivityForResult(audioIntent, TAKE_AUDIO);
}

Monday 11 March 2013

Regular Expressions for Validations

Regular Expressions for Validations

^[0-9]$      it allows only numbers without any limit

^[0-9]{0,10}$   it allows only numbers up-to  minimum 0 to  maximum 10 digits

^[0-9]{1,10}$   it allows only numbers up-to  minimum 1 to  maximum 10 digits

^[0-9.]{0,10}$   it allows only numbers and decimal numbers also up-to  minimum 1 to  maximum 10 digits

^[+]?\\d+(\\.{0,1}(\\d{0,3})\\%{0,1})?$   it allows +ve numbers only and also

 

^     allows(caret)

[]    specific numbers are symbols you want allow  like [0-9] it allows 0 to 9 all numbers

{}  specific limit for # chars appears in string {Min,Max}={0,1} means  in given String # may appears once or not appears

\\ this like OR condition

Count Char Occurrences in Java

public static int count_Chars(String given, char key)
{
int count = 0;
for (int i=0; i < given.length(); i++)
{
if (given.charAt(i) == key)
{
count++;
}
}
return count;
}

Start/Stop GPS Programmatically in Android

private void setGPSOn()
{
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

if(!provider.contains("gps"))
{
//if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}

private void setGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

if(provider.contains("gps"))
{
//if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}

Monday 18 February 2013

Getting Selected Radio Button Value from Radio Group in Android

// Gets a reference to our radio group
// rBtnDigits is the name of our radio group (code not shown)
RadioGroup g = (RadioGroup) findViewById(R.id.rBtnDigits);

// Returns an integer which represents the selected radio button's ID
int selected = g.getCheckedRadioButtonId();

// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);

// Now you can get the text or whatever you want from the "selected" radio button
b.getText();

Friday 1 February 2013

Regular expression for a positive double number in a text box?

public static boolean isDouble(String itemPrice)
{
return itemPrice.matches("^[+]?\\d{0,10}+(\\.{0,1}(\\d{0,3}))?$");
}

double values like True when

5

.5

5.

5.5

When False values like

2..2

3,2

$3

afs

a/.sdf

 

Thursday 31 January 2013

Input-stream to File Generation in Java

Input-stream to File Generation in Java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Convert_InputStream_toFile
{
public static void main(String args[])
{
try
{
File f=new File("outFile.java");
InputStream inputStream= new FileInputStream("InputStreamToFile.java");
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){}
}
}

RequestBuilder in Gwt

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;

String url="http://restro.example.com/download?id=0.1212123455&name=raja";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try
{
Request request = builder.sendRequest("", new RequestCallback()
{
public void onError(Request request, Throwable exception)
{
Window.alert("Request Builder Failed");
}
public void onResponseReceived(Request request, Response response)
{
Window.alert("Request Builder passed"+response.getStatusCode());
}
});
} catch (RequestException e)
{
e.printStackTrace();
}

Wednesday 30 January 2013

HashMap keys and values into ArrayList in java

HashMap hm;
// ...add hm values here...

ArrayList keys = new ArrayList(hm.keySet());
ArrayList values = new ArrayList(hm.values());
ArrayList all = new ArrayList();
all.addAll(hm.keySet());
all.addAll(hm.values());

Tuesday 29 January 2013

GWT SuggestBox Enable and Disable

import com.google.gwt.user.client.DOM;

//pass in your own TextBox when you construct the SB:
TextBox tb = new TextBox();
SuggestBox sb = new SuggestBox(oracle, tb);

// and disable the TextBox it can effect to SuggestBox
tb.setEnabled(false);

// and enable the TextBox it can effect to SuggestBox
tb.setEnabled(true);


public static void setEnabled(SuggestBox sb,boolean enabled)
{
DOM.setElementPropertyBoolean(sb.getElement(), "disabled", !enabled);
}

 
 
 

Thursday 10 January 2013

Android : How To Check If Device Has Camera

In Android, you can use PackageManager , hasSystemFeature() method to check if a device has camera, gps or other features.

See full example of using PackageManager in an activity class.


package com.mkyong.android;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

public class FlashLightActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);

Context context = this;
PackageManager packageManager = context.getPackageManager();

// if device support camera?
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
//yes
Log.i("camera", "This device has camera!");
}else{
//no
Log.i("camera", "This device has no camera!");
}

}
}



Camera flashlight example
You may interest on this example – How to turn on/off camera LED/flashlight in Android.

How To Send Email In Android

In Android, you can use Intent.ACTION_SEND to call an existing email client to send an Email.

See following code snippets :


	Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{"youremail@yahoo.com"});
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));



P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).
Run & test on real device only.
If you run this on emulator, you will hit error message : “No application can perform this action“. This code only work on real device.

1. Android Layout


File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textViewPhoneNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="To : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextTo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress" >

<requestFocus />

</EditText>

<TextView
android:id="@+id/textViewSubject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subject : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextSubject"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</EditText>

<TextView
android:id="@+id/textViewMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:inputType="textMultiLine"
android:lines="5" />

<Button
android:id="@+id/buttonSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send" />

</LinearLayout>




2. Activity


Full activity class to send an Email. Read the onClick() method, it should be self-explanatory.


package com.mkyong.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SendEmailActivity extends Activity {

Button buttonSend;
EditText textTo;
EditText textSubject;
EditText textMessage;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextTo);
textSubject = (EditText) findViewById(R.id.editTextSubject);
textMessage = (EditText) findViewById(R.id.editTextMessage);

buttonSend.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

String to = textTo.getText().toString();
String subject = textSubject.getText().toString();
String message = textMessage.getText().toString();

Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
//email.putExtra(Intent.EXTRA_CC, new String[]{ to});
//email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);

//need this to prompts email client only
email.setType("message/rfc822");

startActivity(Intent.createChooser(email, "Choose an Email client :"));

}
});
}
}



3. Demo


See default scree, fill in the detail, and click on the “send” button.
Android-Send-Email-Example-1

It will prompts your existing Email client to select.
Android-Send-Email-Example-2

In this case, i selected Gmail, and all previous filled in detail will be populated to Gmail client automatically.
Android-Send-Email-Example-3

Note
Android does not provide API to send Email directly, you have to call the existing Email client to send Email.

Download Source Code


Download it – Android-Send-Email-Example.zip (16 KB)

How To Send SMS Message In Android

In Android, you can use SmsManager API or device’s Built-in SMS application to send a SMS message. In this tutorial, we show you two basic examples to send SMS message :

  1. SmsManager API


    	SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);



  2. Built-in SMS application


    	Intent sendIntent = new Intent(Intent.ACTION_VIEW);
    sendIntent.putExtra("sms_body", "default content");
    sendIntent.setType("vnd.android-dir/mms-sms");
    startActivity(sendIntent);




Of course, both need SEND_SMS permission.


<uses-permission android:name="android.permission.SEND_SMS" />



P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).
Note
The Built-in SMS application solution is the easiest way, because you let device handle everything for you.

1. SmsManager Example


Android layout file to textboxes (phone no, sms message) and button to send the SMS message.

File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textViewPhoneNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Phone Number : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextPhoneNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:phoneNumber="true" >
</EditText>

<TextView
android:id="@+id/textViewSMS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter SMS Message : "
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editTextSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:lines="5"
android:gravity="top" />

<Button
android:id="@+id/buttonSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send" />

</LinearLayout>



File : SendSMSActivity.java – Activity to send SMS via SmsManager.


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendSMSActivity extends Activity {

Button buttonSend;
EditText textPhoneNo;
EditText textSMS;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonSend = (Button) findViewById(R.id.buttonSend);
textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
textSMS = (EditText) findViewById(R.id.editTextSMS);

buttonSend.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

String phoneNo = textPhoneNo.getText().toString();
String sms = textSMS.getText().toString();

try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}

}
});
}
}



File : AndroidManifest.xml , need SEND_SMS permission.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mkyong.android"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<uses-permission android:name="android.permission.SEND_SMS" />

<application
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".SendSMSActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>



See demo :
android-send-sms-message-example


2. Built-in SMS application Example


This example is using the device’s build-in SMS application to send out the SMS message.

File : res/layout/main.xml – A button only.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
android:id="@+id/buttonSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send" />

</LinearLayout>



File : SendSMSActivity.java – Activity class to use build-in SMS intent to send out the SMS message.


package com.mkyong.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SendSMSActivity extends Activity {

Button buttonSend;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonSend = (Button) findViewById(R.id.buttonSend);

buttonSend.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

try {

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}



See demo :
android-send-sms-message-example2

android-send-sms-message-example2-1

Download Source Code


Download it – 1. Android-Send-SMS-Example.zip (16 KB)


How To Open An URL In Android’s Web Browser

Here’s a code snippet to show you how to use “android.content.Intent” to open an specify URL in Android’s web browser.


	button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.mkyong.com"));
startActivity(intent);

}

});



Note
For full example, please refer to this – Android button example.

How To Set Default Activity For Android Application

In Android, you can configure the starting activity (default activity) of your application via following “intent-filter” in “AndroidManifest.xml“.

See following code snippet to configure a activity class “logoActivity” as the default activity.

File : AndroidManifest.xml


        <activity
android:label="Logo"
android:name=".logoActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>



For example, let said you have two activities class, and you want to set the “ListMobileActivity” activity as the starting activity of your application.

File : AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mkyong.android"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="List of Mobile OS"
android:name=".ListMobileActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="List of Fruits"
android:name=".ListFruitActivity" >
</activity>
</application>

</manifest>



On the other hand, If you want to set the “ListFruitActivity” activity as your starting activity, just cut and paste the “intent-filter” like following :

File : AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mkyong.android"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="List of Mobile OS"
android:name=".ListMobileActivity" >
</activity>
<activity
android:label="List of Fruits"
android:name=".ListFruitActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


Java Comparable and Comparator Example to sort Objects

Java provides some inbuilt methods to sort primitive types array or Wrapper classes array or list. Here we will first learn how we can sort an array/list of primitive types and wrapper classes and then we will use java.lang.Comparable and java.util.Comparator interfaces to sort array/list of custom classes.

Let’s see how we can sort primitive types or Object array and list with a simple program.









JavaObjectSorting.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36


package com.journaldev.sort;


import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.List;


public class JavaObjectSorting {


    /**

     * This class shows how to sort primitive arrays,

     * Wrapper classes Object Arrays

     * @param args

     */

    public static void main(String[] args) {

        //sort primitives array like int array

        int[] intArr = {5,9,1,10};

        Arrays.sort(intArr);

        System.out.println(Arrays.toString(intArr));

        

        //sorting String array

        String[] strArr = {"A", "C", "B", "Z", "E"};

        Arrays.sort(strArr);

        System.out.println(Arrays.toString(intArr));

        

        //sorting list of objects of Wrapper classes

        List<String> strList = new ArrayList<String>();

        strList.add("A");

        strList.add("C");

        strList.add("B");

        strList.add("Z");

        strList.add("E");

        Collections.sort(strList);

        for(String str: strList) System.out.print(" "+str);

    }

}




Output of the above program is:










1

2

3


[1, 5, 9, 10]

[1, 5, 9, 10]

 A B C E Z




Now let’s try to sort an array of a custom class we have.









Employee.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40


package com.journaldev.sort;


public class Employee {


    private int id;

    private String name;

    private int age;

    private long salary;


    public int getId() {

        return id;

    }


    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    public long getSalary() {

        return salary;

    }


    public Employee(int id, String name, int age, int salary) {

        this.id = id;

        this.name = name;

        this.age = age;

        this.salary = salary;

    }


    @Override

    //this is overriden to print the user friendly information about the Employee

    public String toString() {

        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +

                this.salary + "]";

    }


}




Here is the code I used to sort the array of Employee objects.










1

2

3

4

5

6

7

8

9


//sorting custom object array

Employee[] empArr = new Employee[4];

empArr[0] = new Employee(10, "Mikey", 25, 10000);

empArr[1] = new Employee(20, "Arun", 29, 20000);

empArr[2] = new Employee(5, "Lisa", 35, 5000);

empArr[3] = new Employee(1, "Pankaj", 32, 50000);

//sorting employees array using Comparable interface implementation

Arrays.sort(empArr);

System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));




When I tried to run this, it throws following runtime exception.










1

2

3

4

5

6


Exception in thread "main" java.lang.ClassCastException: com.journaldev.sort.Employee cannot be cast to java.lang.Comparable

    at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)

    at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)

    at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)

    at java.util.Arrays.sort(Arrays.java:472)

    at com.journaldev.sort.JavaSorting.main(JavaSorting.java:41)




Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo(T obj)method which is used by sorting methods, you can check any Wrapper, String or Date class to confirm this. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.

After implementing Comparable interface in Employee class, here is the resulting Employee class.









Employee.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50


package com.journaldev.sort;


import java.util.Comparator;


public class Employee implements Comparable<Employee> {


    private int id;

    private String name;

    private int age;

    private long salary;


    public int getId() {

        return id;

    }


    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    public long getSalary() {

        return salary;

    }


    public Employee(int id, String name, int age, int salary) {

        this.id = id;

        this.name = name;

        this.age = age;

        this.salary = salary;

    }


    @Override

    public int compareTo(Employee emp) {

        //let's sort the employee based on id in ascending order

        //returns a negative integer, zero, or a positive integer as this employee id

        //is less than, equal to, or greater than the specified object.

        return (this.id - emp.id);

    }


    @Override

    //this is required to print the user friendly information about the Employee

    public String toString() {

        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +

                this.salary + "]";

    }


}




Now when we execute the above snippet for Arrays sorting of Employees and print it, here is the output.










1

2


Default Sorting of Employees list:

[[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]




As you can see that Employees array is sorted by id in ascending order.

But, in most real life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on the age. This is the situation where we need to use Comparator interface becauseComparable.compareTo(Object o) method implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.

Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.

Here is how we can create different Comparator implementation in the Employee class.










1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32


/**

     * Comparator to sort employees list or array in order of Salary

     */

    public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return (int) (e1.getSalary() - e2.getSalary());

        }

    };


    /**

     * Comparator to sort employees list or array in order of Age

     */

    public static Comparator<Employee> AgeComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return e1.getAge() - e2.getAge();

        }

    };


    /**

     * Comparator to sort employees list or array in order of Name

     */

    public static Comparator<Employee> NameComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return e1.getName().compareTo(e2.getName());

        }

    };




We can use these comparator to pass as argument to sort function of Arrays and Collections classes.










1

2

3

4

5

6

7

8

9


//sort employees array using Comparator by Salary

Arrays.sort(empArr, Employee.SalaryComparator);

System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Age

Arrays.sort(empArr, Employee.AgeComparator);

System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Name

Arrays.sort(empArr, Employee.NameComparator);

System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr));




Here is the output of the above code snippet:










1

2

3

4

5

6


Employees list sorted by Salary:

[[id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000]]

Employees list sorted by Age:

[[id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000]]

Employees list sorted by Name:

[[id=20, name=Arun, age=29, salary=20000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=1, name=Pankaj, age=32, salary=50000]]




So now we know that if we want to sort any custom object array/list, we need to implement Comparable to provide default sorting and we should implement Comparator to provide specific sorting.

We can also create separate class that implements Comparator interface and then use it.

Here is the final classes we have explaining java Comparable and Comparator.









Employee.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82


package com.journaldev.sort;


import java.util.Comparator;


public class Employee implements Comparable<Employee> {


    private int id;

    private String name;

    private int age;

    private long salary;


    public int getId() {

        return id;

    }


    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    public long getSalary() {

        return salary;

    }


    public Employee(int id, String name, int age, int salary) {

        this.id = id;

        this.name = name;

        this.age = age;

        this.salary = salary;

    }


    @Override

    public int compareTo(Employee emp) {

        //let's sort the employee based on id in ascending order

        //returns a negative integer, zero, or a positive integer as this employee id

        //is less than, equal to, or greater than the specified object.

        return (this.id - emp.id);

    }


    @Override

    //this is required to print the user friendly information about the Employee

    public String toString() {

        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +

                this.salary + "]";

    }


    /**

     * Comparator to sort employees list or array in order of Salary

     */

    public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return (int) (e1.getSalary() - e2.getSalary());

        }

    };


    /**

     * Comparator to sort employees list or array in order of Age

     */

    public static Comparator<Employee> AgeComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return e1.getAge() - e2.getAge();

        }

    };


    /**

     * Comparator to sort employees list or array in order of Name

     */

    public static Comparator<Employee> NameComparator = new Comparator<Employee>() {


        @Override

        public int compare(Employee e1, Employee e2) {

            return e1.getName().compareTo(e2.getName());

        }

    };

}




Here is the separate class implementation of Comparator interface that will compare two Employees object first on their id and if they are same then on name.









EmployeeComparatorByIdAndName.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14


package com.journaldev.sort;


import java.util.Comparator;


public class EmployeeComparatorByIdAndName implements Comparator<Employee> {


    @Override

    public int compare(Employee o1, Employee o2) {

        int flag = o1.getId() - o2.getId();

        if(flag==0) flag = o1.getName().compareTo(o2.getName());

        return flag;

    }


}




Here is the test class where we are using different ways to sort Objects in java.









JavaObjectSorting.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43


package com.journaldev.sort;


import java.util.Arrays;


public class JavaObjectSorting {


    /**

     * This class shows how to sort custom objects array/list

     * implementing Comparable and Comparator interfaces

     * @param args

     */

    public static void main(String[] args) {


        //sorting custom object array

        Employee[] empArr = new Employee[4];

        empArr[0] = new Employee(10, "Mikey", 25, 10000);

        empArr[1] = new Employee(20, "Arun", 29, 20000);

        empArr[2] = new Employee(5, "Lisa", 35, 5000);

        empArr[3] = new Employee(1, "Pankaj", 32, 50000);

        

        //sorting employees array using Comparable interface implementation

        Arrays.sort(empArr);

        System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));

        

        //sort employees array using Comparator by Salary

        Arrays.sort(empArr, Employee.SalaryComparator);

        System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr));

        

        //sort employees array using Comparator by Age

        Arrays.sort(empArr, Employee.AgeComparator);

        System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr));

        

        //sort employees array using Comparator by Name

        Arrays.sort(empArr, Employee.NameComparator);

        System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr));

        

        //Employees list sorted by ID and then name using Comparator class

        empArr[0] = new Employee(1, "Mikey", 25, 10000);

        Arrays.sort(empArr, new EmployeeComparatorByIdAndName());

        System.out.println("Employees list sorted by ID and Name:\n"+Arrays.toString(empArr));

    }


}




Here is the output of the above program:










1

2

3

4

5

6

7

8

9

10


Default Sorting of Employees list:

[[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]

Employees list sorted by Salary:

[[id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000]]

Employees list sorted by Age:

[[id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000], [id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000]]

Employees list sorted by Name:

[[id=20, name=Arun, age=29, salary=20000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=1, name=Pankaj, age=32, salary=50000]]

Employees list sorted by ID and Name:

[[id=1, name=Mikey, age=25, salary=10000], [id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000]]




The java.lang.Comparable and java.util.Comparator are powerful interfaces that can be used to provide sorting objects in java.