Sunday, 28 December 2014

Skipping Gradle Tasks

Background

Gradle simply speaking is a build tool like Apache ant but it does more that that and in an efficient way. It handles dependency management as well. You can say -

Gradle = Apapch Ant + Apache Ivy

In the background Gradle is all Groovy.  So if you are aware of groovy writing tasks in gradle is no big deal.

Make sure you have JDK configured and gradle installed.



Gradle Task Build Life Cycle

Gradle has 3 distinct phases -
  1. Initialization
  2. Configuration
  3. Execution

For more details on each of the phases refer Gradle Build Life Cycle . To quickly understand this build life cycle put following code in build.gradle file and run it - 

logger.lifecycle("This is executed during configuration phase");
task A() {
    logger.lifecycle("This is also executed during configuration phase");
    doFirst {
      logger.lifecycle('In task A : This is executed first in the execution phase.')
    }
    doLast {
        logger.lifecycle("In task A :This is executed last in execution phase");
    }    
}


and the output is



Hope you got the idea. Configuration and Execution phases are what we are going to concentrate on.

Lets first see how to write dependents Tasks in gradle.

Writing Dependent Tasks in Gradle


Create a file build.gradle and copy following code in it.

task A(dependsOn: 'B') {
    
    doLast {
        logger.info("In task A");
    }    
}

task B(dependsOn: 'C') {
    doLast {
        logger.info("In task B");
    }
}

task C {

    doLast {
        logger.info("In task C");
    }

}


Above code essentially declares three gradle tasks - A, B and C. Also there are dependencies between them. Notices the dependsOn keyword in bracket. Task A depends on Task B which in turn depends on Task C. Now lets run this. Output is -



Note 1 :

You can also define type of a Task. There are various predefined tasks in gradle. Something like -

task copyFiles(type: Copy, dependsOn: 'SomeAnotherTask') {
    from 'src/main/documentation'
    into 'build/target/documentation'
}


Note 2 :

You can also simply say - 

task A << {
    logger.lifecycle("In task A : Execution phase");
}


The '<<' symbol you see is just a shortcut to execute thing is Execution phase. This defines a task called A with a single closure to execute.

Ok now lets come to the intended purpose of this post which is - how to skip tasks.

Skipping Tasks in Gradle

Goal : Goal is to skip task A and all subsequent tasks that A depends on. Lets say we decide this with a property that we provide to gradle from commandline. Lets call it 'skipA'. If 'skipA' is provided in command line arguments we do not execute any task.

For this lets use onlyIf first.

task A(dependsOn: 'B') {
    onlyIf {
        !project.hasProperty('skipA')
    }
   
    doLast {
        logger.lifecycle("In task A");
    }   
}

task B(dependsOn: 'C') {
    doLast {
        logger.lifecycle("In task B");
    }
}

task C {
    doLast {
        logger.lifecycle("In task C");
    }
}


and the output is




Lets analyze what happened here.Yes Task A was skipped as we intended but what about other tasks they were run.

Don't argue that you can put onlyIf and condition in all tasks :) you are smarter than that!

Note : One important point to note is onlyIf is executed during execution phase and by that time gradle has figured out what all tasks it needs to run. Skipping a single task will not skip the task the skipped task depends on. We need to add skipping logic in configuration phase.

There is another way to do this and that is to set enabled = false; inside a task. This will skip the given task. Also we need two other things.

  1. Implement skipping logic in Configuration phase.
  2. Remove all the tasks that the task to be skipped was depending on (This needs point 1.)

So lets see how can we do that. Copy following code in build.gradle file -

task A(dependsOn: 'B') {
    if(project.hasProperty('skipA')) {
        logger.lifecycle("Skipping Project : " + project.name);
        enabled = false;
        dependsOn = [];
    }
   
    doLast {
        logger.lifecycle("In task A");
    }   
}

task B(dependsOn: 'C') {
    doLast {
        logger.lifecycle("In task B");
    }
}

task C {
    doLast {
        logger.lifecycle("In task C");
    }
}


and the output is


Yes we got what we wanted. Now lets see how we did it.

  • First of all see the if statement in task A. It is outside any doFirst() or doLast() method. This ensures it will be run in configuration phase.
  • Then we checked out condition. If it is true then we set enabled  = false for the task. This will skip task A.
  • To stop other tasks from running that A depends on we removed all those tasks by saying dependsOn = []; Again note this worked because we did it in configuration phase.

Related Links

Friday, 26 December 2014

Suppressed exceptions in java 7

Background

In Java 7 new feature was introduced - try-with-resources statement where resources will be autoclosed. We will come to that. But this feature introduced another important topic and that is suppressed Exceptions and that is what we will discuss in this post.


Suppressed Exception in Java 6

Consider simple try-catch block

public class HelloWorld {

    public static void main(String args[]) {
        try {
            test();
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    public static void test() throws Exception {
        try {
            System.out.println("In try block");
            throw new NullPointerException("NPE from try block");
        } finally {
            System.out.println("In finally block");
            throw new NullPointerException("NPE from finally block");
        }
    }

}

and the output is : 

In try block
In finally block
java.lang.NullPointerException: NPE from finally block

Where did the NPE thrown from try block go ? Well it was lost or ignored. One dirty way to retain the cause Exception is to chain it. 

To summarize what above part says is that exception thrown from finally block eats up the exception that might have been thrown from try block.

Now lets head over to Java 7 try-with-resource statement to see what it has for us.

Try With Resources statement in Java7

Hope you are aware what try-with-resource statements are. If not please first go through try-with-resource section of Whats new in Java7 post.

As you know resource that can be used in try-with-resource statement needs to implement Closable or AutoClosable interface. Lets define one such resource.

public class DefectiveResource implements AutoCloseable {

    public DefectiveResource() {
        System.out.println("This is defective constructor");
        throw new NullPointerException("From DefectiveResource constructor");
    }

    public DefectiveResource(String str) {
        System.out.println("This is non - defective constructor.");
    }

    public void process() {
        throw new NullPointerException("From DefectiveResource process");
    }

    @Override
    public void close() throws Exception {
        throw new NullPointerException("From DefectiveResource close");
    }

}


Ok we have our resource. Lets go ahead and test it out.


Case 1 : Exception thrown while instantiating a resource

Consider following code - 

public class HelloWorld {

    public static void main(String args[]) {

        try {
            testSuppressException();
        } catch (Exception ex) {
            System.out.println(ex);
        }

    }

    public static void testSuppressException() throws Exception {
        try (DefectiveResource dr = new DefectiveResource()) {
            System.out.println("In testSuppressException");
        }

    }
}


Output would print -

This is defective constructor
java.lang.NullPointerException: From DefectiveResource constructor

meaning try block was not executed. That's right if exception is thrown while creating resources in try-with-resource block try block is not even executed. Don't even bother thinking about closing resource as it was not created in the first place.

Case 2: Exception is thrown from try-with-resource block as well as try block

 This case is a little tricky. When I say Exception is thrown from try-with-resource block it mean exception is thrown during closing of resources. If exception occurs while instantiating resource it will fall under case1. So Exception is thrown while closing resource (which occurs as a part of try-with-resource statement)  and exception is also thrown from try block.

public class HelloWorld {

    public static void main(String args[]) {

        try {
            testSuppressException();
        } catch (Exception ex) {
            System.out.println(ex);
        }

    }

    public static void testSuppressException() throws Exception {
        try (DefectiveResource dr = new DefectiveResource("Test")) {
            System.out.println("In testSuppressException");
            dr.process();
        }

    }

}

And the output is : 

This is non - defective constructor.
In testSuppressException
java.lang.NullPointerException: From DefectiveResource process

Now lets analyze the code. You can see "In testSuppressException" in the output that means instantiating went through. process() method must have thrown Exception and close() method would have too. But we see only Exception thrown by process() method.

That's right Exception thrown while closing resource from try-with-resource statement was suppressed by the Exception from try block. You can get the suppressed Exception as follows - 

public class HelloWorld {

    public static void main(String args[]) {

        try {
            testSuppressException();
        } catch (Exception ex) {
            System.out.println(ex);
            final Throwable[] suppressedException = ex.getSuppressed();
            if(suppressedException.length > 0)
                System.out.println("Suppresed Exception : " + suppressedException[0]);
        }

    }

    public static void testSuppressException() throws Exception {
        try (DefectiveResource dr = new DefectiveResource("Test")) {
            System.out.println("In testSuppressException");
            dr.process();
        }

    }

}


and output is - 

This is non - defective constructor.
In testSuppressException
java.lang.NullPointerException: From DefectiveResource process
Suppresed Exception : java.lang.NullPointerException: From DefectiveResource close

Hope it's clear now that Exception from try block suppressed Exception that occurred from closing resource in try-with-resource statement. 

I will go 2 step ahead and tell you this. Try-with-resource create an implicit finally statement and tries to close resources in it. and this exception is suppressed by exception from try block.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed. 

That means if you provide an explicit finally statement that's ok but resources will be closed before this executed. Meaning the implicit finally block I was talking about will be completed before this.

And this brings me to 3rd case.

Case 3 : Exception thrown from explicit finally block with try-with-res statement

So if Exception is thrown from try-with-resource block (during close), it is also thrown from try block and then again from finally block - 


public class HelloWorld {

    public static void main(String args[]) {

        try {
            testSuppressException();
        } catch (Exception ex) {
            System.out.println(ex);
            final Throwable[] suppressedException = ex.getSuppressed();
            if(suppressedException.length > 0)
                System.out.println("Suppresed Exception : " + suppressedException[0]);
        }

    }

    public static void testSuppressException() throws Exception {
        try (DefectiveResource dr = new DefectiveResource("Test")) {
            System.out.println("In testSuppressException");
            dr.process();
        }finally {
            throw new NullPointerException("From explicit finally block");
        }

    }

}

and the output here is - 

This is non - defective constructor.
In testSuppressException
java.lang.NullPointerException: From explicit finally block

Lets go step by step. Resource instantiation went through. Exception is thrown from try block and then while closing (from implicit finally block if you are imagining that way). So far as per above case exception from try block takes precedence and suppressed exception occurring from close() in try-with-resource statement. But when explicit finally block is executed it again ignores all these exceptions and throws it's own (similar to Java 6 example at the top).

Also if exception was thrown while creating/instantiating resources as in case 1 then try block will not be executed and again exception from explicit finally block would override this.

Bottom line : If your explicit finally block throws Exception all your previous exceptions are eaten up.

Important point of this post was to explain that the Exception from close() is suppressed by Exception from try block.

Note : The close methods of resources are called in the opposite order of their creation.

Related Links




Saturday, 20 December 2014

CodeChef problem

Question : 


STATEMENT

There are n events. Each has a start time and end time. You wish to attend maximum of such events.

NOTE:If start time of one event is same as end time of other you cannot attend both. You can imagine some time to travel from event1 to event2.

INPUT

The first line will contain an integer T, denoting the number of test cases.

Each test case contains several lines.

The first line of each test case will contain an integer N, denoting the number of events.

The next N lines, one for each event, contain two space separated integers, starttime and endtime.

1 <= T <= 10
1 <= N <= 10000
0 <= starttime < endtime <= 1000000000

OUTPUT

For each test case, output a single integer denoting the maximal number of events that you can attend.
EXAMPLE
INPUT

2
5
0 5
0 2
3 5
3 4
5 6
6
0 8
8 10
11 12
11 15
2 5
7 9
OUTPUT

3
3
EXPLANATION

In the first case you can attend events (0, 2), (3, 4), (5, 6)



Solution


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;

/**
 * 
 * @author athakur
 *
 */
public class Quark1 {

    public static void main(String args[]) throws IOException {
        
         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
         PrintWriter writer = new PrintWriter(System.out,true);
        
         int noOfTestCases = Integer.parseInt(reader.readLine());
        
         for(int i=0; i<noOfTestCases; i++) {
             int noOfEvents = Integer.parseInt(reader.readLine());
             Event[] events = new Event[noOfEvents];
             for(int j=0; j< noOfEvents; j++) {
                 String[] times = reader.readLine().split(" ");
                 events[j] = new Event(Integer.parseInt(times[0]),Integer.parseInt(times[1]));
             }
             writer.println(getMaxEvents(events));
         }
    }
    
    private static int getMaxEvents(Event[] events) {
        Arrays.sort(events);
        int i=0;
        int count = 1;
        for (int j=1; j<events.length;j++) {
            if(events[j].startTime > events[i].endTime) {
                count++;
                i=j;
            }
        }
        return count;
    }
    
    static class Event implements Comparable<Event>
    {
        int startTime;
        int endTime;
        
        public Event(int startTime, int endTime) {
            this.startTime = startTime;
            this.endTime = endTime;
        }

        @Override
        public int compareTo(Event event) {
            return this.endTime > event.endTime ? 1 : (this.endTime < event.endTime ? -1 : 0);
        }
    }
    
}
 

Explanation : 

First we sort the events based on the finish time because we want to attend earliest events first. Now if end times if two events are same we can attend either. So we don't bother about it. On sorting such events can have sequential positioning (one after the other) in either way. Next we start from first event in sorted events list. We can only attend next event if it's start time is greater (mind even equals will not work as we have to consider commute delay) than the end time of current event. Current event is tracked with i variable where as next event is tracked with j.

Friday, 19 December 2014

Android Programming Tips and Tricks


Showing Toast in Android

//Toast shown for  short period of time
Toast.makeText(getApplicationContext(), "Toast Message", Toast.LENGTH_SHORT).show();

//Toast shown for long period of time
Toast.makeText(getApplicationContext(), "Toast Message", Toast.LENGTH_LONG).show();
 
OR using custom layout for your toast

Toast myToast = new Toast(getApplicationContext());
myToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
myToast.setDuration(Toast.LENGTH_LONG);
myToast.setView(myLayout);
myToast.show();


Getting all running Apps in Android

    private List<String> getRunningApps() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager packageManager = getPackageManager();
        final List<RunningAppProcessInfo> runningProcesses = activityManager.getRunningAppProcesses();
        List<String> runningAppNames = new ArrayList<String>();
        for(RunningAppProcessInfo processInfo : runningProcesses) {
            CharSequence appName = null;
            try {
                appName = packageManager.getApplicationLabel(packageManager.getApplicationInfo(processInfo.processName, PackageManager.GET_META_DATA));
                runningAppNames.add(appName.toString());
            } catch (NameNotFoundException e) {
                Log.e(TAG,"Application info not found for process : " + processInfo.processName,e);
            }
        }
        return runningAppNames;
    }


Above code required permission -

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

Killing Background App

You can use  -

 ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses(packageName);


You can't kill the app in the foreground (your App) by this. You need to finish(). Also note this is for API 8 and above and needs permission KILL_BACKGROUND_PROCESSES.

Dynamically Creating Layout

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
Button button = new Button(this);
button.setText(appName);
linearLayout.addView(button, layoutParams);

Adding Scroll bar over a Layout

LinearLayout rootLinearLayout = new LinearLayout(this);
LinearLayout linearLayout = new LinearLayout(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ScrollView scrollView = new ScrollView(this);
scrollView.addView(linearLayout, layoutParams);
rootLinearLayout.addView(scrollView, layoutParams);

Closing current Activity

finish();
return;

Note : You should put a return statement after that finish, because the method that called finish will be executed completely otherwise.

Getting Resources

getResources().getString(R.string.app_name);
getResources().getLayout(R.layout.myLayout); 
getResources().getColor(R.color.MY_RED);

Resources are under res directory. For example String resources are in res/string.xml  with content like - 

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Simple App Killer</string>
    <string name="about">About</string>

</resources>

Getting View or Activity Content View

findViewById(R.id.myView);
this.getWindow().getDecorView().findViewById(android.R.id.content);
this.findViewById(android.R.id.content);
this.findViewById(android.R.id.content).getRootView(); 

Note : R.layout.* are layouts you provide (in res/layout, for example).android.R.layout.* are layouts that ship with the Android SDK. Infact R.layout is actually shortcut for your.package.R.layout

Creating Menu

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.test_menu, menu);
        return true;
    }

You need to override onCreateOptionsMenu method and use MenuInflater to inflate your menu. You also need to provide menu .Create a file name test_menu.xml under res/menu folder with content like -

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
   
<item android:id="@+id/about"
          android:title="@string/about" />

</menu>

To set onclick on the menu items you need to override onOptionsItemSelected method as follows -

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
             case R.id.about:
                Toast.makeText(getApplicationContext(), "This App is created by Aniket Thakur", Toast.LENGTH_LONG).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    } 

Getting Managers

ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
PackageManager packageManager = getPackageManager();

Note : these manages will not be available before onCreate() method. Also recollect these managers form second layer of Android architecture after application layer. These managers talk to the kernel layer using native libraries and android runtime.

Hiding Action Bar App Icon and App Name

getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false)



Note : This requires API level 11 or above.

Saving Persistent Data

When you application needs to save some persistent data you should always do it in onPause() methods. Because if android OS kills your process then onStop() and onDestroy() methods are never called.

Starting new Activity with startActivity() and startActivityForResult() methods

You can start a new activity by creating an intent object and then calling 
  • startActivity(Intent) [Simply starts new Activity]
  • startActivityForResult(Intent, int) [Start new Activity expecting some result from new activity to be sent to the activity from which new activity was started].
You can also send some extra information in the intent using Intent classes putExtra() method. Later you can reference the intent that started the new activity in the new activity as getIntent() and then retrieve the additional information as getStringExtra().

MyActivity :

Intent intent = new Intent(this, MyNewActivity.class);
intent.putExtra("musicEnabled", "yes");
startActivity(intent);



MyNewActivity :

Intent intent = getIntent();
String musicEnabled = intent.getStringExtra("musicEnabled");
//more logic here   

If you use startActivityForResult(Intent, int) method [if you need to activity you are starting to return some data back to the activity that started it] then you need to call -

MyActivity  :

static private final int GET_TEXT_REQUEST_CODE = 1;
Intent intent = new Intent(this, NewActivity.class);
startActivityForResult(intent,GET_TEXT_REQUEST_CODE);


you can then retrieve the returned result in a callback method -

MyActivity  :

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("NewActivity", "Entered onActivityResult()");
       
        if(resultCode == Activity.RESULT_OK && requestCode == GET_TEXT_REQUEST_CODE){
            myTextView.setText(data.getStringExtra("MY_VALUE"));
        } 
    } 


and then in your NewActivity class you have to set the result with RESULT_OK code as follows -

MyNewActivity  :

        String input = myEditText.getText().toString();
        Intent intent  = new Intent();
        intent.putExtra("MY_VALUE",input );
        setResult(Activity.RESULT_OK, intent);
        finish();


Showing Notifications

Code is as follows - 

Intent browseIntent = new Intent(Intent.ACTION_VIEW, Uri
        .parse("http://google.com"));
PendingIntent pendingIntent = PendingIntent.getActivity(
        MainActivity.this, 0, browseIntent,
        PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder notificationBuilder = null;
notificationBuilder = new Notification.Builder(
        MainActivity.this)
        .setSmallIcon(android.R.drawable.stat_sys_warning)
        .setAutoCancel(true).setContentIntent(pendingIntent)
        .setContentTitle("Notification Title")
        .setContentText("Notification Content Text")
        .setTicker("Ticker Text");

NotificationManager notificationManager = (NotificationManager) MainActivity.this
        .getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(12345, notificationBuilder.build());


Ticker Text will be seen as -



and you can see the actual notification on pulling down the notification bar



You can also set your own layout as view for the notification. For that you can do -

RemoteViews mContentView = new RemoteViews(MainActivity.this

        .getPackageName(), R.layout.activity_main);

notificationBuilder = new Notification.Builder(

        MainActivity.this).setContent(mContentView); 



Note: PendingIntent is a special type of intent that allows 3rd party code (in this case Notification Manager) to execute application code with the same permission as the application. When you click on above notification browser should open and display google.com.

More to Come....
PS : This list will keep updating. If you want me to add something in above list please provide it in the comments.

Good Read

Difference between Running Task and Running Process in Android

Background

Tasks and processes are different in Android. I am going to discuss the same in this post. I ran into this question when I was trying to figure out the difference between the calls

final List<RunningTaskInfo> runningTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

and

final List<RunningAppProcessInfo> runningProcesses = activityManager.getRunningAppProcesses();

So lets see the difference.


Running Task and Running Process in Android

Android has Linux kernel. So process is similar to processes in Linux. Each process can have multiple threads. When a process starts it is single thread execution by default. This thread is called the main thread or UI thread. You may have other worker or asynchronous threads running in a process.

Task or Application on the other hand can be visualized as set of activities in an application. It is possible that each activity in the task is configured to run in different processes. Same goes for other entitles of Android - services, providers etc. Infact components of different tasks/applications can run in same process (provided that the applications share the same Linux user ID and are signed with the same certificates).

When System memory is low of running application an older process is killed. Again note this may have components of different application.

activityManager.getRunningTasks(Integer.MAX_VALUE)


Above will give you Running tasks or rather lets call it application consisting of set of activities. (List of RunningTaskInfo objects). This in turn will have two main things.
  1. baseActivity : component launched as the first activity in the task
  2. topActivity : activity component at the top of the history stack of the task

and

activityManager.getRunningAppProcesses()


Above will give all running processes in the System. Since it is a process it will have associated pid (processId) and `uid (userId). Some of the important fields here are -
  1. processName : The name of the process that this object is associated with
  2. pid : The pid of this process; 0 if none
  3. uid : The user id of this process.
  4. pkgList : All packages that have been loaded into the process.

To get all running app name we do something like - 

    public List<String> getRunningApps() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager packageManager = getPackageManager();
        final List<RunningAppProcessInfo> runningProcesses = activityManager.getRunningAppProcesses();
        List<String> runningAppNames = new ArrayList<String>();
        for(RunningAppProcessInfo processInfo : runningProcesses) {
            CharSequence appName = null;
            try {
                appName = packageManager.getApplicationLabel(packageManager.getApplicationInfo(processInfo.processName, PackageManager.GET_META_DATA));
                runningAppNames.add(appName.toString());
            } catch (NameNotFoundException e) {
                Log.e(TAG,"Application info not found for process : " + processInfo.processName,e);
            }
        }
        return runningAppNames;
    }

 In above code we are essentially getting information about all running processes. Then with the help of process name of each such process we are getting corresponding application package.


Interesting Read

First of all you need to understand what you can kill and what not. By android's point of view an application is not like other OSes. An android application consists of many components (activities, broadcast receivers, services, most important tasks etc) which are packed in a package. A package can have more that one processes running depending on its components running. 

Now the interesting part is that an android package isn't considered (by android) "killed" or "stopped" if any or all of its processes have killed, in fact a package can still running even with no processes running at all. 

You can see this effect if you start an emulator start a program (i.e. Browser) and then kill its process via DDMS, after that go to the application's package settings (Settings --> Applications --> Manage Applications --> All --> Browser), you can see the "Force Stop" button enabled, this means that the application is still running (from android's point of view). 

What happened here is that the application has one or more tasks "frozen". That is, android has saved the state of the application's activities (task or tasks) and so the package is still running or better if the user returns to it he will land on the last thing he was doing. Now if you click the "Force Stop" button, android will discard all of these "frozen" tasks and when the user returns to the application he will see the first activity. 

A Task is something you cannot kill (since froyo) only the user (from "Force Stop" button), the system or a third party application which is signed with the same key of the system can do that (and maybe a root capable application but I have not confirmed this). On the other hand a Process is something you can kill and reclaim the memory it uses, as long as you follow some restrictions:
  1. You have the "android.permission.KILL_BACKGROUND_PROCESSES" permission.
  2. The processes are not system or root processes.
  3. The process is not belonging to a component which is persistent.
  4. The process is not a critical for the system to operate by any other means.

Besides the no 1 rule you do not have to do something about them, android will take care of this.

ActivityManager has a handy function you can use in order to kill all of the processes a package has at once. When you invoke it android will kill any process can be killed and thus freeing up some memory. However the state of the tasks for this package will be saved and when the user returns to the application he will see the last thing he was doing unless the system itself has killed them. This can occur either because it needs resources or the state was saved long time ago (about 30 minutes). The side-effect is that because users are thinking that all applications are like in desktop operating systems, they do not believe that the application is really closed but this is the life with android.

(Source - SO)

Related Links

Friday, 12 December 2014

Difference between Comparator and Comparable in Java

Background

How do we sort numbers in Java. Following is the simple program to do that - 

    public static void main(String args[]) {
        int[] myArray = new int[]{5,10,2,1,6};
        Arrays.sort(myArray);
        for(int no : myArray) {
            System.out.print(no + " ");
        }
    }

And we get the output as : 1 2 5 6 10 

Same goes for Collections as well.

But that is for simple numbers. How do we sort complex custom Objects. For example lets say you have Student Objects and you need to sort them on the basis of their age or some other scenario may require them to be sorted alphabetically by name. In this post we will see exactly how to do this.

Ordering Custom Objects


Lets create our Student class first.

Student.java


public class Student {
    
    private String name;
    private int age;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
}



For simplicity I have just kept two parameters - name and age. Before we proceed to create group of students and order them we need to answer a question -

What is the natural ordering ? The answer will vary depending on the scenario for which you are writing your code. In this scenario we will take age as natural ordering criteria.

Why did we answer above question ? Because it is the basis of the title of this post - Difference between Comparator and Comparable in Java.

Difference between Comparator and Comparable in Java

Implementing Comparable means "I can compare myself with another object." This is typically useful when there's a single natural default comparison.

Implementing Comparator means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.

In our case we decided age will be our natural ordering. So we will handle age comparison in Comparable interface where as handle name in Comparator.

Note : Both Comparator and Comparable are interfaces. You need to implement them. Your model class which needs to be naturally ordered implements Comparable interface where as you need to create a separate class that implements Comparator to handle non natural ordering. When you call methods like sort we need to supply instance of this class that implemented Comparator interface.

 Comparable interface is in package java.lang whereas Comparator interface is in java.util package. Also when you implement Comparable interface you override a.compareTo(b) method where as in case of Comparator you override compare(a, b). Don't worry about the technicality. We will see this with example.

Implementing Comparable interface - natural ordering

As I mentioned earlier with reference to our Student object I am going to use age as natural ordering criteria.

Lets rewrite our Student class which will now implement Comparable interface.


public class Student implements Comparable<Student> {
    
    private String name;
    private int age;
    
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
    
    @Override
    public int compareTo(Student o) {
        return (this.age > o.age ? 1 : (this.age < o.age ? -1 : 0));
    }
}


Notice the logic in compareTo() method. We return 1 if current object is higher in order, -1 if lower and 0 if same. Lets test this now - 

public class OrderingTester {

    

    public static void main(String args[]) {

        Student[] allStudents = new Student[] { new Student("John", 21),

                new Student("Rita", 19), new Student("Sam", 26),

                new Student("Claire", 16) };


        System.out.println("Before natural sorting");

        for(Student student : allStudents) {

            System.out.println(student);

        }

        Arrays.sort(allStudents);

        System.out.println("After natural Sorting");

        for(Student student : allStudents) {

            System.out.println(student);

        }

    }

}

And the output is - 

Before natural sorting
Student [name=John, age=21]
Student [name=Rita, age=19]
Student [name=Sam, age=26]
Student [name=Claire, age=16]
After natural Sorting
Student [name=Claire, age=16]
Student [name=Rita, age=19]
Student [name=John, age=21]
Student [name=Sam, age=26]


That's how natural ordering/comparable interface work. Now lets move on to comparator interface.

Implementing Comparator interface - Custom ordering

Lets start by writing our comparator class - 

public class StudentNameComparator implements Comparator<Student> {

    @Override
    public int compare(Student student1, Student student2) {
        return student1.getName().compareTo(student2.getName());
    }

}

and now lets test this - 

public class OrderingTester {
    
    public static void main(String args[]) {
        Student[] allStudents = new Student[] { new Student("John", 21),
                new Student("Rita", 19), new Student("Sam", 26),
                new Student("Claire", 16) };
        
        System.out.println("Before custom sorting");
        for(Student student : allStudents) {
            System.out.println(student);
        }
        Arrays.sort(allStudents, new StudentNameComparator());
        System.out.println("After custom Sorting");
        for(Student student : allStudents) {
            System.out.println(student);
        }
    }

}

And the output is - 

Before custom sorting
Student [name=John, age=21]
Student [name=Rita, age=19]
Student [name=Sam, age=26]
Student [name=Claire, age=16]
After custom Sorting
Student [name=Claire, age=16]
Student [name=John, age=21]
Student [name=Rita, age=19]
Student [name=Sam, age=26]


Logic in compare() method that we override on implementing Comparator interface is same as compareTo() method that we override on implementing Comparable interface.

Notice how we just gave the array to sort in Arrays.sort() in natural sorting where as we gave the comparator with custom ordering logic as a separate argument to sort method.



Hope this clarifies the difference. Let me know if you still have any doubts or questions.

Java 8 changes in Comparator and Comparable interface

 With introduction of function interface and Lambda expressions in Java 8 there are changes made in comparable and comparator  interfaces as well. 
  • Both comparable and comparator interfaces are functional interfaces.
Just to remind you interfaces can now also have static methods and they do not affect the functional status of an interface.

Now let's visit our old problem of sorting student. As per what we discussed we said let age be used to do natural sorting (used comparable interface for that) and for sorting with name (custom sorting) we use comparator interface. But what if we 1st want to compare using name and if that matches then compare using age. Lets see how that would workout

public class StudentNameComparator implements Comparator<Student> {

    @Override
    public int compare(Student student1, Student student2) {
        int result =  student1.getName().compareTo(student2.getName());
        if (result != 0) return result;
        return student1.getAge() - student2.getAge();
    }

}


Sure that works out but there is a smarter way. One that Java 8 provides. Well see that now.

public class StudentNameComparator implements Comparator<Student> {

    @Override
    public int compare(Student student1, Student student2) {
        Comparator<Student> c = Comparator.comparing(s -> s.getName());
        c = c.thenComparingInt(s -> s.getAge());
        return c.compare(s1, s2);
    }

}


NOTE : comparing static method - Accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator<T> that compares by that sort key.


Related Links


Tuesday, 9 December 2014

Enum Data Types in Java

Background

Sometime we need to program to restrict use inputs. Lets take a scenario - you are opening a pet store. As a starter you decide only to provide  - Dogs, Cats and Parrots. Next you have to design a Java program to provide the pet to customers. One way would be as follows - 

class PetStore {
    
    public static final String CATEGORY_DOGS = "Dogs";
    public static final String CATEGORY_CATS = "Cats";
    public static final String CATEGORY_PARROTS = "Parrots";
    
    public void getPet(String petType) {
        switch(petType){
        case CATEGORY_DOGS : System.out.println("You are opting for a pet Dog");
                            break;
        case CATEGORY_CATS : System.out.println("You are opting for a pet Cat");
                            break;
        case CATEGORY_PARROTS : System.out.println("You are opting for a pet Parrot");
                            break;
        default : System.out.println("We do not provide other pet animals");
        }
    }
}


It serves the purpose. But it does not stop user from entering Lion, Tiger does it ? Program would fall back to default saying we do not provide other pet Animals. But Lion, Tiger are not pet in the first place. One way to restrict user input is declaring an Enum. Lets come to that.



Using Enums

enum PetTypes {
    DOGS,CATS,PARROTS
}

class PetStore {
    
    public void getPet(PetTypes petType) {
        switch(petType){
        case DOGS : System.out.println("You are opting for a pet Dog");
                            break;
        case CATS : System.out.println("You are opting for a pet Cat");
                            break;
        case PARROTS : System.out.println("You are opting for a pet Parrot");
                            break;
        }
    }
}

Now you have successfully restricted user from entering one of the three allowed values. That is not it Enums has other advantages too.Lets come to those. Lets say you also need to store the number of available pet of each category. You can store that in enum too. Each enum value can have multiple attributes.


enum PetTypes {
    DOGS(10),CATS(7),PARROTS(9);
    
    int availableUnits;
    
    //enum constructors are implicitly private
    PetTypes(int availableUnits) {
        this.availableUnits = availableUnits;
    }

    public int getAvailableUnits() {
        return availableUnits;
    }
    
}

class PetStore {
    
    public void getPet(PetTypes petType) {
        switch(petType){
        case DOGS : System.out.println("You are opting for a pet Dog.");
                            break;
        case CATS : System.out.println("You are opting for a pet Cat");
                            break;
        case PARROTS : System.out.println("You are opting for a pet Parrot");
                            break;
        }
        System.out.println("Available units are : " + petType.getAvailableUnits());
    }
}


You can test it by

    public static void main(String args[])
    {
        new PetStore().getPet(PetTypes.CATS);
    }


You will get :

You are opting for a pet Cat
Available units are : 7

Note : When you say DOGS(10), corresponding constructor is called i.e PetTypes(10).

Enums are better than a bunch of constants because it provides type‐safe
checking.

Important Points

  • Enums are implicitly private, static and final. 
  • Each declared enum implicitly inherits java.lang.Enum.
  • You can use valueOf() and name() methods on enums.
  • You can compare enums with == operator.
  • You cannot use new operator on enums. Not even inside enum definition. Outside you cannot because constructor is implicitly private. 
  • Enums cannot be local meaning you cannot declare them inside a method. They should be declared and defines inside of a top level class or an interface.

Question : 

 1. What happens when you compile the following code - 

enum PetTypes {
    int availableUnits;             //  #1
    DOGS(10),CATS(7),PARROTS(9);    //  #2
    
    //enum constructors are implicitly private
    PetTypes(int availableUnits) {
        this.availableUnits = availableUnits;
    }

    public int getAvailableUnits() {
        return availableUnits;
    }
 }

Above enum definition is incorrect and will not compile. You need to declare enum elements first before any other attributes. In short you need to interchange line #1 and #2 for above code to compile. (JLS reference)
NOTE : You can also create an enum from a String. This is helpful when working with older
code. The String passed in must match exactly, though.

Eg.

PetTypes s1 = PetTypes.valueOf("DOGS"); // DOGS
PetTypes s2 = PetTypes.valueOf("dogs"); // exception



NOTE : The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

NOTE : Another thing that you can’t do is extend an enum. The values in an enum are all that are allowed. You cannot add more at runtime by extending the enum.

You can also have abstract method in an enum in which case each enum will have to implement the abstract method -

    public enum PetTypes {
        DOGS {
            public void printHours() { System. out .println("9am-3pm"); }
        }, CATS {
            public void printHours() { System. out .println("9am-5pm"); }
        }, PARROTS {
            public void printHours() { System. out .println("9am-7pm"); }
        }, RABBIT {
            public void printHours() { System. out .println("9am-5pm"); }
        };
        public abstract void printHours();
    }


If we don’t want each and every enum value to have a method, we can create a default
implementation and override it only for the special cases:

     public enum PetTypes {
        DOGS {
            public void printHours() { System. out .println("9am-3pm"); }
        }, CATS {
            public void printHours() { System. out .println("9am-5pm"); }
        }, PARROTS , RABBIT ;
        public void printHours() { System. out .println("9am-9pm"); };
    } 
  
NOTE : If in your enum class all you have are types of that enums you can skip the semicolon. So you can do something like -

    enum Flavors {
        VANILLA, CHOCOLATE, STRAWBERRY
    }


But you cannot do something like -

    enum Flavors {
        VANILLA, CHOCOLATE, STRAWBERRY //not allowed, need semicoln here
       
        Flavors(){}
    }


This will give compilation error. If you have anything more than enum declarations you need to add a semicolon. Also as stated earlier enums should be the 1st thing in the enum structure.

NOTE : The ordinal() method of an enum returns its corresponding int value. Like arrays,
enums are zero based. Remember that the index of an enum may change when you recompile
the code and should not be used for comparison.

Related Links

Monday, 8 December 2014

Method Overloading resolution in Java

Background

Instead of giving an overview of what this post entails let me give you a quick problem to solve. Lets say you have few methods

public static void execute( int data) {System.out.println("int")}
public static  void execute( short data) {System.out.println("short")}
public static  void execute( Object data) {System.out.println("object")}
public static  void execute( String data) {System.out.println("string")}


and I call following methods - 

public static void main(String[] args) {
    byte byt = 3;
    execute(byt); // 1st call
    execute(10); // 2nd call
    Integer i = 6;
    execute(6); // 3rd call
    execute("Test"); // 4th call
}

What would be the output ?
It would be - 

short
int
object
string

Surprised? Wondering ?

Will solve the mystery in a minute :). Lets get our basics clear first and then there would be no need for me to go ahead and explain the outputs.

Few points to note about the question -
  1. The methods you see have same name, return type but different types of arguments. This is called method overloading. For more details refer Overriding Methods in Java - How it works?
  2. Next we are calling methods some of which that do not exactly match the ones which are defined. Like calling execute() with byte 3. There is no method which takes byte as argument. But there is short, int and even Object argument methods that are compatible. Note the word "compatible" but only one is chosen from it - and we saw it was short in this case. Java as all programming languages has rules which dictates these things which is exactly what we will see in some time.

Rules for method overloading resolution

  1.  Java Compiler always tries to choose the most specific method available with least number of modifications to the arguments.
  2. Next point is about Boxing / Unboxing. Java developers wanted the old code to work exactly the same a sit used to work before boxing / unboxing.
  3. With points 1 and 2 in mind the order in which preference is given is -

    Widening (size wise)[Minimum first] > Boxing/Unboxing > variable arguments.

 Primitive types sizes in Java

  • byte: The byte data type is an 8-bit signed two's complement integer.
  • short: The short data type is a 16-bit signed two's complement integer.
  • int: By default, the int data type is a 32-bit signed two's complement integer.
  • long: The long data type is a 64-bit two's complement integer. 
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point.
  • boolean: The boolean data type has only two possible values: true and false.
  • char: The char data type is a single 16-bit Unicode character.

Primitive types default values in Java



Now give the question in backgrounds section another try.

With above rules in mind lets try to solve the question posted at the top of this post.

First call was

byte byt = 3;
execute(byt); // 1st call

As per above rule most preferred was would be widening. There are two options here. Widen byte (8bit) to a short (16 bit) or an int (32 bit). Widening with lowest size is preferred (which is short in this case) and hence we got short printed.

Next is

execute(10); // 2nd call

and is a direct call as we have execute method with int parameter. So int is printed.

Next we have

Integer i = 6;
execute(6); // 3rd call

Since we do not have a method with Integer as argument we will go for next best case and that is polymorphic superclass. Object is superclass of all objects implicitly. So we get object printed.

Lastly we have

execute("Test"); // 4th call

Again we have execute method with String which is chosen here. Again straight forward.

Note : Widening is preferred over boxing/unboxing which is preferred over variable arguments. By variable arguments I mean something like

public void execute (int ...x)

Hope this clarifies all doubts regarding our original question.

Note : Java Compilation will fail if there are no matches or ambiguous matches for a function call.

Example of no matches : 

Methods available are

public static  void execute( short data) {System.out.println("short")}
public static  void execute( byte data) {System.out.println("byte")}

and you call

execute (10) // execute (int)

Example of ambiguous matches : 


Methods available are

public static  void execute( int data1, long data2) {System.out.println("int-long")}
public static  void execute( long data1, int data2) {System.out.println("long-int")}

and you call

execute (1,2) // execute (int,int)

Related Links


Sunday, 30 November 2014

Starting a new Process programmatically from Java

Background

In this post we will see how we can run any process from java programmatically. In specific I will show how can we compile a java file from a Java process. We can very well use Runtime.getRuntime().exec() method to start the process but in this post I am going to demonstrate using ProcessBuilder class.

Code

    public static void executeJavacCommand() throws IOException {

        List<String> paramsExecute = new ArrayList<String>();
        paramsExecute.add("C:\\Program Files\\Java\\jdk1.6.0_31\\bin\\javac.exe");
        paramsExecute.add("-cp");
        paramsExecute.add(".");
        paramsExecute.add("HelloWorld.java");
        ProcessBuilder pBuilder = new ProcessBuilder(paramsExecute);
        Process process = pBuilder.start();
        Reader reader = new InputStreamReader(process.getErrorStream());
        int ch;
        while((ch = reader.read())!= -1)
            System.out.print((char)ch);
        reader.close();

    }

Note1 : In above code I am only printing the error stream of the process but you can manipulate the output stream as well as provide input stream to the process.
Note 2:  You can also see my previous post on how to get the java executable paths. You can programmatically derive those and use it in above code.


Related Links

t> UA-39527780-1 back to top