"A little progress everyday adds up to big results"
Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Sunday, 11 November 2018

Fixing a Java bug at runtime without restarting the JVM process

    1. Have you missed something while developing a Java application, that resulted in a bug?
    2. Is that buggy application already running in production?
    3. Are you concerned about the impact of the scheduled (or unscheduled) downtime to deploy your fix?
    4. Do you want to fix the bug in production without redeploying or restarting the application?
    If your answers to all the above questions are "yes", then this post is for you! 
    Let us start with a sample (buggy) Java application

    package com.jrf.sampleapp;
    
    import java.io.InputStreamReader;
    import java.lang.String;
    import java.util.Scanner;
    
    public class SimpleCalculator {
     private static String add(long addend, long augend) {
      return "Sum is " + (addend+augend);
     }
    
     private static String subtract(long minuend, long subtrahend) {
      return "Difference is " + (minuend-subtrahend);
     }
    
     private static String multiply(long multiplier, long multiplicand) {
      return "Product is " + (multiplier*multiplicand);
     }
    
     private static String divide(long dividend, long divisor) {
      return "Ratio is " + (dividend/divisor);
     }
    
     public static void main(String[] args) {
      long input1, input2;
      String command;
    
      Scanner scanner = new Scanner(new InputStreamReader(System.in));
      command = scanner.next();
    
      while(!command.equalsIgnoreCase("exit")) {
       input1 = scanner.nextLong();
       input2 = scanner.nextLong();
    
       switch(command.toLowerCase()) {
        case "add":
         System.out.println(add(input1, input2));
         break;
    
        case "subtract":
         System.out.println(subtract(input1, input2));
         break;
    
        case "multiply":
         System.out.println(multiply(input1, input2));
         break;
    
        case "divide":
         System.out.println(divide(input1, input2));
         break;
    
        default:
         System.out.println("Use \"add x y | subtract x y | multiply x y | divide x y | exit\"");
         break;
       }
    
       command = scanner.next();
      }
     }
    }
    
    
    This is a simple console Java application to perform the basic binary mathematical operations repeatedly until the "exit" command is issued. When we run this, we get the following output:

    Sum is 11
    subtract 3 4
    Difference is -1
    multiply 8 7
    Product is 56
    divide 12 3
    Ratio is 4
    divide 100 0
    Exception in thread "main" java.lang.ArithmeticException: / by zero
     at com.jrf.sampleapp.SimpleCalculator.divide(SimpleCalculator.java:21)
     at com.jrf.sampleapp.SimpleCalculator.main(SimpleCalculator.java:49)
    
    
    Oops!!! The divisor zero check is missing in the "divide" method, resulting in unexpected termination of the application with an ArithmeticException. Now, assume that you had realized your mistake after deploying the application, but, before someone issued a zero divisor. Could you have avoided the mishap without bringing your application down? Perhaps you could have!!! Here is how. 

    Basically, we want to dynamically patch the Java class at runtime, with absolute zero downtime. We all know that a JVM executes bytecode resulting from a compilation. So, we are trying to modify the bytecode at runtime. Here comes our Java's superhero, Instrumentation, to the rescue!  

    Instrumentation is a way to inject/modify bytecode at runtime. Instrumentation can be done either at the time of loading a class or after it is loaded. Here we are going to use the latter since our application's main class "SimpleCalculator" has already been loaded. Since a lot of resources on Java Instrumentation are available online, let us directly jump into writing an agent to fix the bug.

    package com.jrf.agent;
    
    import java.io.ByteArrayInputStream;
    import java.lang.instrument.ClassFileTransformer;
    import java.security.ProtectionDomain;
    
    import javassist.ClassPool;
    import javassist.CtClass;
    import javassist.CtMethod;
    
    public class JavaRuntimeFixApplier implements ClassFileTransformer {
     public byte[] transform(ClassLoader loader, String className,
       Class classBeingRedefined, ProtectionDomain protectionDomain,
       byte[] classfileBuffer) {
      byte[] byteCode = classfileBuffer;
    
      try {
       byteCode = retransform(className, byteCode);
      } catch (Throwable e) {
       e.printStackTrace();
      }
    
      return byteCode;
     }
    
     private byte[] retransform(String className, byte[] original) throws Exception {
      byte[] modifiedByteCode = original;
    
      switch(className) {
       case "com/jrf/sampleapp/SimpleCalculator":
        ClassPool classPool = ClassPool.getDefault();
        CtClass ctClass = classPool.makeClass(new ByteArrayInputStream(modifiedByteCode));
        CtMethod method = ctClass.getDeclaredMethod("divide", 
         new CtClass[] {CtClass.longType, CtClass.longType});
     
        method.insertBefore("if ($2 == 0) {" +
           "return \"Cannot divide by zero\";" +
              "}");
     
        modifiedByteCode = ctClass.toBytecode();
        ctClass.detach();
        break;
      }
    
      return modifiedByteCode;
     }
    }
    
    
    This is the main transformer class, which performs the bytecode modification. To compile the new source code

    if ($2 == 0) {
     return "Cannot divide by zero";
    }
    
    
    and generate the corresponding bytecode, we have used the Javassist library. The transformer code is pretty self-explanatory. If the fully qualified class path matches "com/jrf/sampleapp/SimpleCalculator", we are inserting the above code at the beginning of the "divide" method that takes 2 long arguments. The "$2" in the above code represents the 2nd argument ("divisor") in the "divide" method. The main Agent Class, that applies this transformer goes like this:

    package com.jrf.agent;
    
    import java.lang.instrument.Instrumentation;
    import java.lang.instrument.UnmodifiableClassException;
    
    public class JavaRuntimeFixerAgent {
     public static void agentmain(String args, Instrumentation instrumentation) {
      try {
       addTransformers(args, instrumentation);
      } catch (Exception e) {
       e.printStackTrace();
      }
     }
    
     private static void addTransformers(String args, Instrumentation instrumentation) 
      throws ClassNotFoundException, UnmodifiableClassException {
    
      instrumentation.addTransformer(new JavaRuntimeFixApplier(), true);
       
      if (!instrumentation.isRetransformClassesSupported()) {
       System.out.println("Class retransformation is not supported in this version of JVM");
       return;
      }
    
      Class clazz = Class.forName("com.jrf.sampleapp.SimpleCalculator");
      instrumentation.retransformClasses(clazz);
     }
    }
    
    
    The important thing to note here is that some JVMs do not support class bytecode redefinition once they are loaded. In such cases, this approach would not work.

    These 2 classes need to be packaged into a JAR before it is loaded into the target application's memory. The JAR's manifest file looks like

    Agent-Class: com.jrf.agent.JavaRuntimeFixerAgent
    Can-Redefine-Classes: true
    Can-Retransform-Classes: true
    Class-Path: javassist.jar
    
    
    Modifying the classes at runtime requires the "Can-Redefine-Classes" and "Can-Retransform-Classes" properties to be true. The first line defines the class, whose "agentmain" method is where to start executing the agent from.

    Now that we have the application running and the agent to fix the application handy. What next!? To apply the fix by loading the agent in the application's JVM. In order to do so, let us define a loader class as follows

    package com.jrf.loader;
    
    import com.sun.tools.attach.AgentInitializationException;
    import com.sun.tools.attach.AgentLoadException;
    import com.sun.tools.attach.AttachNotSupportedException;
    import com.sun.tools.attach.VirtualMachine;
    import java.io.*;
    
    public class JavaRuntimeFixLoader {
     public static void main(String[] args) throws AgentInitializationException, 
      AgentLoadException, AttachNotSupportedException, IOException {
    
      if (args.length != 2) {
       System.out.println("Usage: java JavaRuntimeFixLoader  ");
       System.exit(-1);
      }
      
      VirtualMachine jvm = VirtualMachine.attach(args[1]);
      jvm.loadAgent(args[0]);
      jvm.detach();
     }
    }
    
    
    Just run this loader with either the absolute path to the agent JAR or the agent JAR's path relative to the target application and the target application's process id. If you do not see any error in both the loader and the target application, congratulations! Your fix is successfully (and magically) patched at runtime. Let us test it.

    add 5 6
    Sum is 11
    subtract 3 4
    Difference is -1
    multiply 8 7
    Product is 56
    divide 12 3
    Ratio is 4
    divide 100 0
    Cannot divide by zero
    divide 100 10
    Ratio is 10
    exit
    

    Using this approach, at runtime, one can 
    • Overwrite methods 
    • Perform argument checks at the beginning of methods 
    • Surround a method under a try-catch block 
    • Overwrite complete classes 
    • and do many more... 
    all without recompiling, redeploying or restarting the original application. 

    The complete source code of the example explained here is available at https://github.com/sureshprakash/JavaRuntimeFixer. In one terminal run the "make sampleapp" command to compile and run the sample calculator application. After this, in another terminal run the "make instrument" command that will compile the agent and apply the necessary fix at runtime.

    Let us appreciate the power of Java's Instrumentation!

    Monday, 12 January 2015

    A C program without main

                   As soon as you see the title, you might be wondered whether this is possible. But, it's actually possible.  

    #include<stdio.h>

    #define modify(t, r, a, i, n, s) i ## t ## a ## r
    #define change modify(a, n, i, m, a, l)

    int change()
    {
        printf("C without main!\n");
        return 0;
    }


                If you still don't trust this program, compile and execute it. Shocked ? In fact, there is a main in this program, but hidden. This is based on the concept of token pasting. What happens here is, change is initially replaced by modify(a, n, i, m, a, l). The arguments are then replaced as follows
    t = a
    r = n
    a = i
    i = m
    n = a
    s = l

               The statement i ## t ## a ## r gets changed to m ## a ## i ## n, which is then concatenated as main. Eventually, 'change' is changed to 'main'.  Since all these steps take place even before compilation (at the macro expansion stage), the compiler does not throw an error.
    Now, become a magician by showing this trick to your friends! 

    C Programming : Display only the significant digits after decimal point

    Problem:
     
                 In C++ programming, if we give the statements,

    float pi = 3.1400f ;
    cout<<pi ;

    only 3.14 ( significant digits ) will be shown. 
              
                 But, in C program , if we give
    float pi = 3.1400f ;
    printf ( "%f", pi ) ;

    3.140000 will be displayed. 
                
    The '%g' format specifier:      
           Of course we can use %0.2f. But, we may not always know how many decimal digits are there? In such situations we can make use of %g,


    float pi = 3.1400f ;
    printf ( "%g", pi ) ;

    will print 3.14
     
    Now, say 'Hi' to %g

    C Programming : The (input) buffer problem

                          Usually in C programming, whatever we type gets stored in the keyboard buffer (temporary storage) and then the CPU takes input from the buffer. If a scanf is used to read input, this buffer is inspected first. If the input is available in the buffer itself, it is taken directly and the scanf statement terminates. Only if the buffer does not have the requested input, the user is prompted for input.
                 
                        Whenever we input a number (int, float or double), we give the number and press enter to specify that our input is ready to be taken. Both (number and enter) are stored in the buffer.

                             After enter is pressed, the number gets stored in the (int, float or double) variable. But, where does the enter go? Yes, it remains in the buffer. Next time when a character or string is to be given as input, this enter will be taken directly from the keyboard buffer and we will not be prompted to input the character or string.

    Example:
    1.#include<stdio.h>
    2.
    3.int main()
    4.{
    5.          int num ;
    6.          char ch ;
    7.          printf ( "Number: " ) ;
    8.          scanf ( "%d", &num ) ;
    9.          printf ( "\nCharacter: " ) ;
    10.        scanf ( "%c", &ch ) ;
    11.        printf ( "%cBye", ch ) ;
    12.        return 0 ;
    13. }

    Output:
    Number: 2
    Character:
    Bye

    Explanation:
    2 is stored in num and '\n' ( enter ) is stored in ch.

    Solution 1:
    To get rid of this let us use getchar() before the second scanf(), that is at line number 10. getchar() takes the enter from the buffer. But, since we didn't assign it to any variable, it gets wasted (removed from the buffer).

    Solution 2:
    Instead of using getchar(), we may get the character twice, that is use scanf ( "%c %c", &ch, &ch ) ; instead of scanf ( "%c", &ch ) ; In this case, first enter is stored in ch and later, the input we give replaces it.

    The best solution:Which one of the above do you think is the best solution? If you think it is solution 1, then you are wrong. If you think it is solution 2, then also you are wrong. Both of the above are only solutions, but not the best. The best and right solution is to clear the buffer using the inbuilt function.

                  If you are a Turbo C programmer, use the following statement before line 10.
    fflush (stdin);

                    If you are a gcc programmer, use the following statement before line 10.
    __fpurge (stdin); // It is double 'underscore' followed by fpurge
    and include <stdio_ext.h>

    Do not get caught in the buffer jail!

    A C program without semicolon

    C program to display “India” without using ';' anywhere in the program:

                               Before writing this program, we should first understand what printf returns and its prototype. The function declaration of printf is
    int printf ( const char *, ... ) ;
                              It takes variable number of arguments, displays the string till a NULL character is found and returns the number of characters printed.

    Now, the program:

    #include<stdio.h>
    void main()
    {
        if ( printf ( "India" ) )
        {
        }
    }

    The printf () returns 5 in this case. Hence, the 'if' condition is true, but, we are not doing anything inside the block of 'if'.

    Next time if someone asks you whether you can write a C program without semicolon, reply 'yes'

    C Programming: Let the user specify the number of decimal digits after the decimal point

                       In a C program, what will we do if we want to display only specific number of digits (which is determined at run time, like user input) after decimal point? We can get the number from the user, put it in switch() and provide a case for each individual number, as follows.


    int num;
    float pi = 3.1415
    93;
    printf ( "Enter the number of decimal digits to be shown: ");
    scanf ( "%d", &num );
    switch ( num )
    {
    case 1 : printf ( "%0.1f", pi ); break ;
    case 2 : printf ( "%0.2f", pi ); break ;
    ...................
    }

                        But, is it possible to give for each and every number? Moreover, this is not the correct way of programming. Use it in a single statement, instead of switch.


    int num;
    float pi = 3.141593;
    printf ( "Enter the number of decimal digits to be shown: " );
    scanf ( "%d", &num );
    printf ( "%*.*f", 0, num, pi );
     
    This will display 'num' digits after the decimal point. In the last statement, the first asterisk is replaced by 0 and the second asterisk by the value of 'num'.

    Give full freedom to the user!

    Sunday, 16 September 2012

    Clear explanation of Java's Ugly Syntax

    Introduction:
                   Most of the Java programmers might have worked with the (Ugly) syntax of an anonymous class. This post will cleanly explain the Ugly syntax (especially with Anonymous classes) of Java. For example,  consider the button click event in Java Swing.

    class EventHandler implements ActionListener
    {
             public void actionPerformed(ActionEvent e)
             {
                         // Code that handles the event
             }
    }

    // Somewhere else
    ActionListener e = new EventHandler();
    button_object.addActionListener(e);


    This is a very straight forward way, where each and every process is done step by step. Now, before moving on to the equivalent ugly syntax code, we must be knowing 5 Java concepts.

    1. Interface object concept:
                                     An interface can have an object to which, an object of one of the classes implementing it, can be assigned. For example, in the above code, ActionListener is an interface and e is an object of it. We have instantiated e by invoking the new operator on the EventHandler class (which implements the ActionListener interface).

    2. Anonymous object concept:
                                     The synonym for the term 'Anonymous' is 'nameless'. There might be some situations when we would require the object of a particular class, in just one statement. In such cases to avoid 2 lines of code, we may go for an Anonymous object. 

    For example:

    ActionListener e = new EventHandler();

    button_object.addActionListener(e);


    could be written as

    button_object.addActionListener(new EventHandler());

                               This is done purely to reduce the lines of code; however doing so affects the readability of the code, whereas the efficiency of the code remains unaltered.

    3. Method implementation specific to an object:
                                    While writing multi-threading code in Java, one might have written code something like this.

    Thread t = new Thread()
    {
              public void run()
              {
                       // Thread code
              }
    };


    One can say that this code implements the method run(), which is specific to the object t.

    4. Method implementation specific to an instance of an interface:
                              This is nothing but the combination of the concepts 1 and 3. This concept will be well understood with the following examples.

    Runnable t = new Thread()
    {
         public void run()
         {
              // Thread code

         }
    };


    Using this concept with the ActionListener interface,

    ActionListener e = new EventHandler()
    {
              public void actionPerformed(ActionEvent e)
             {
                         // Code that handles the event
             }
    };


    5. Anonymous class concept:
                                  Bit tricky to understand, but would be simple with an example. The syntax of an anonymous class is
    new <Implemented interface/Super class>()
    {
               // Code inside the class
    }

    For example,
    class A
    {
           // block of A
    }
    interface B
    {
           // block of B
    }
    class C extends A implements B
    {
           // block of C
    }
    class Main
    {
            B b = new B()
            {
                   // methods of the interface B are implemented here
            };
    }

                    
    Putting them all together:                        
                                Now, we are going to put them all together. So, the click event code (mentioned in the second paragraph) can be written as follows.

    button_object.addActionListener ( new ActionListener()
    {
            public void actionPerformed(ActionEvent e)
            {
                // Code that handles the event
            }
    } );


                    Well...! Hope you might have understood. If not, please don't worry, you will understand it when you use these concepts in your code.

    Now tell me, isn't Java interesting and challenging ?

    Sunday, 9 September 2012

    Running Java Applet in free website domain

                               As a Java programmer, everyone will know that Java can be embedded in Web pages as Applets. This post will show how an Applet can be embedded in a Web page, which is hosted in a free domain.

    Step 1: Make the Java applet source file ready.
    Step 2: Compile the Java applet to get the class file.
    Step 3: Write an HTML code, embedding the Applet.
    Step 4: Create a free domain using one of the free hosting services like 000webhost
    Step 5: Upload the .class and the .html files into the same directory

    Share the URL with your friends and enjoy!

    Saturday, 4 August 2012

    My first presentation on Android application development

    A surprise:
                      When I had been to internship at IIIT, Hyderabad during my fourth semester holidays, I kept reporting my work to my HOD (Dr. J. Akilandeswari) via email. She replied that it was her wish that I take a presentation on "Android application development" after my return to college, as I did my internship project on Android platform. Being a lover of sharing knowledge, I was overwhelmed with joy and immediately replied my acceptation to my HOD through mail.

    Longing days:
                           After returning to my college, HOD specified a Saturday (August 4th, 2012) for doing the presentation and asked me to contact my lecturer, Mr. Murali, to make the hall arrangements. Everything were ready on 31st July and I was waiting for the day to come. At last, the day came and I did the presentation on "An introduction to Android application development" at PG auditorium of my college approximately about one hour and fifteen minutes for the 3rd year IT students. 

    Presentation:
                             This was the first time in my life doing a continuous presentation for more than an hour. Though I had stage fear during previous presentations and seminars, I couldn't find stage fear in myself during this presentation (might be because, I was doing announcements in different classes the previous week, regarding programming club, Aspirations - a programming contest conducted by Infosys every year and was taking classes in the programming club of my college). I think because of my confidence, I could explain clearly, whatever I intended to tell.

    Feedback:
                            Some of my friends appreciated my confidence, professionalism and accent. Some added that they could understand the concepts very clearly, though they have attended Android workshops. Because of the lack of time, I could not complete explaining whatever I had prepared. But then, I was happy about the feedback given by my friends. I should really thank my HOD for giving me such a golden opportunity.

    "Practice makes a man perfect"

    Saturday, 30 June 2012

    Comparing floating point numbers in programming languages

                        Some times, while programming, we might need to handle floating point numbers. In such cases, we cannot compare them simply by giving '==' operator, because, we cannot expect the numbers to be perfectly equal, if the number of values beyond the decimal point goes unlimited. In such cases, we can follow these steps.

    (Assuming we need the floating point numbers to be equal for 4 digit precision)
    For C/C++:
    #define PRECISION_DIGITS 4
    #define DELTA pow(10, - PRECISION_DIGITS)

    For Java:
    final int PRECISION_DIGITS = 4;
    final float DELTA = Math.pow(10, - PRECISION_DIGITS);

    and in the program, you can compare like this
    if ( abs ( value1 - value 2 ) < DELTA ) // For Java change abs to Math.abs
    {
           // Statements for value1 == value2
    }
    else
    {
          // Statements for value1 != value2
    }

    More references regarding the floating point comparison is available in this site.

    Tuesday, 26 June 2012

    The power of NDK in Android

                         While developing android applications, sometimes, one might want to perform CPU intensive operations like huge number of calculations. In such cases, the time taken for performing those operations might be so high, so that the user gets frustrated. Of-course, one can run such operations as a Service ( background task ) and intimate the user on completion via notification; but, there is a better alternative in Android, called Native Devleopment Kit ( NDK ), which allows development from C/C++ instead from Java.

                           It is simply the equivalent of Java Native Interface ( JNI ) in Java. This is nothing but, calling C/C++ functions from Java. If one has a very basic knowledge of JNI, then it's not at all a matter for him/her to develop application in NDK. I faced this situation once, when I developed Speaker Recognizer application for android as a part of my internship at IIIT, Hyderabad. I had written the entire code in Java and the code executed nearly for about 40 seconds on a device with operational frequency 600 MHz. When I reported this to my project guide, Dr. Kishore S. Prahallad, he suggested me NDK.

                          I thought that C/C++ would be some 2 or 3 times faster than Java. But, to my surprise, my code executed in just 4 seconds on the same device, which is almost 10 times faster. I was wondered and realized that C and C++ are nearly 10 times faster than Java on Android devices. So, if you want to perform CPU intensive operations on android, I suggest NDK. The entire tutorial is available at this site.

    Tuesday, 29 May 2012

    My coding conventions

                                      When I started programming, I didn't follow any conventions in naming the variables and functions. But, as days passed by, I started using standard conventions for naming. The naming conventions I use for programming are

    class - Every word in title case - standard Java convention

    method - Every word except the first one in title case - standard Java convention

    variable - Every word in lower case, each word separated by an underscore '_'

    non-final, non-static, member variable - Every word in lower case, each word separated by an underscore '_' and prefixed with 'm_'

    non-final, static, member variable - Every word in lower case, each word separated by an underscore '_' and prefixed with 's_'

    final variables - Every word in upper case, each word separated by an underscore '_'

    Other conventions used by me:
    Task pending - // TODO: - Convention followed by Eclipse IDE

    Optimization possible - //::

    Test code which has to be removed later - surrounded by lines // TEST //

    My programming journey

    Before starting to learn programming:
                                      I started programming ( of course 'C' )  in late 2009, when I was studying in my 11th standard. Before I was taught programming, I just went through the text book ( two volumes for Computer Science and C was in the second volume ) given to us. In the exercises part of the 'C' lesson, I saw a numerous problems ( to convert Fahrenheit to Celsius, to find the number of days between two dates, to find the perfect number, etc ). As Computer is not a subject in school days ( though I had studied Computer during my 8th standard in Matriculation ), I was wondered to see those problems and was admired how one could solve them.

    Initial programming classes:
                                       Later, the most awaited day came. We were taught C. But, then, initially we were taught the history of C and then theoretical parts like keywords, tokens, etc. Then, we were taught how to program. At this point, I must thank my Computer Teacher Mr. Yuvaraj. Initially I was very blank.

    A program written on a paper:
                                       Then, my cousin ( Ms. Usha ) got married to Mr. Shivaraman. He asked me to write a simple program which calculates the total, average, result, etc of a 10th student. It was the time when there was no system in my house. I tried to write that program in a notebook. It went to 2 or 3 pages. After that, one day, I went to my cousin's ( Mr. Kannan ) house and typed that program by seeing the notebook ( and it was the time, I didn't know typing ). I searched for every letter and typed. I didn't compile the program, till I finish typing the entire code.
                              
    Type-over mode and compile-time errors:
                                       Moreover, the cursor was in 'Type-over' mode. I didn't know how to correct it. If I had left any line, I typed everything once again starting from that line. After I completed typing the entire code, I compiled. I got 25 errors ( Turbo C compiler ). I couldn't trace out the problem and I left it on that day.

    Run-time errors:
                                      Later, in school, when I was telling this story, my friend , Vikram, told that it was not 'studio.h' and it's 'stdio.h'. Then, I changed it, some one or two errors were there. After I correct, I ran it. But, the results produced were not as expected. I checked all the conditions. When I asked for help from my cousin ( Mr. Kannan ), he gave me a program and asked me to use it. But then, I was not completely satisfied. I came to know that I had missed '&' in scanf statements. Then, I started learning programming little by little.

                                    And later, I learned C++ in 12th. Again C was taught in 1st and 2nd semesters. C++ in depth in 3rd semester. I must thank Mr. K. Saravanan and Mr. S. Lakshmanan for making me understand the coding concepts deeper. I learned Java during my 4th semester on my own and at the end of second year, during my fellowship, I started developing android applications.
                                      

    Sunday, 27 May 2012

    Android: NullPointerException with findViewById

    I was developing an android application for 'Speaker Recognition' at IIIT, Hyderabad under the guidance of Dr. Kishore S. Prahallad as my fellowship project. I was very new to the android development ( approximately one and half weeks ).

    I had a scenario where, I had to show a custom toast with differing text when the Name field is empty or the name entered is existing. I wrote a function as follows and called it with the resource ids from R class. The application crashed unexpectedly on running.

        private void notifyError(int id)
        {
        LayoutInflater in = getLayoutInflater() ;
        View layout = in.inflate(R.layout.toast_layout, (ViewGroup) findViewById ( R.id.toast_layout_root ) ) ;
       
        ImageView im = ( ImageView ) findViewById ( R.id.image ) ;
        im.setImageResource(R.drawable.warning) ;
       
        TextView warn = ( TextView ) findViewById ( R.id.message ) ;
        warn.setText ( id ) ;
       
        Toast toast = new Toast ( getApplicationContext() ) ;
        toast.setView(layout) ;
        toast.setGravity(Gravity.CENTER, 0, 0) ;
        toast.setDuration(Toast.LENGTH_SHORT) ;
        toast.show() ;
        }

    When I debugged, I found that null is being assigned to the im and warn objects. But, couldn't know what was the problem. I google it for about 3 hours, but of no use. Later on having a closer look, I found out, View.findViewById() is different from Activity.findViewById(). So, I changed the code to:

        ImageView im = ( ImageView ) layout.findViewById ( R.id.image ) ;
        im.setImageResource(R.drawable.warning) ;
       
        TextView warn = ( TextView ) layout.findViewById ( R.id.message ) ;
        warn.setText ( id ) ;

    And then, it worked.