Tuesday, 16 October 2012

Values set in EditText visible only when clicked..android problem fix..tested on HTC wildfire

Problem:
Sometimes, values set in EditText is displayed properly in android emulator but it does not show on device(tested with HTC wildfire). It shows only when the field is clicked and disappears when not focused.

Solution:
Set the theme before calling the setcontent() in oncreate.
It can be done in the following way...
setTheme(android.R.style.Theme);

Monday, 24 September 2012

Connect to remote mysql db with PHP webservice, and parse the JSON response object returned using JAVA

Hi, here is a sample code on how to connect to a remote mysql db using a php and parse the JSON response object returned


                  HttpClient httpclient = new DefaultHttpClient();

                 Inputstream is;
                 HttpPost httppost = new HttpPost("http://www.hostname.com/files/getbrowsedata.php");
               HttpResponse response = httpclient.execute(httppost);
               HttpEntity entity = response.getEntity();
                 is = entity.getContent();
        }catch(Exception e){
               Log.e("log_tag", "Error in http connection "+e.toString());
                      }
       

        //convert response to string
        try{
               BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
               StringBuilder sb = new StringBuilder();
               String line = null;
               while ((line = reader.readLine()) != null) {
                       sb.append(line + "\n");
               }
               System.out.println("sb::" +sb);
                String result=sb.toString();
               is.close();
       

        }catch(Exception e){
               Log.e("log_tag", "Error in http connection "+e.toString());
         }

//parse the JSON response object
 try{
       
        JSONObject json = new JSONObject(result);
        JSONArray json_array = json.getJSONArray("display");
       
            for (int i = 0; i < json_array.length(); i++) {
                JSONObject result_json_object = json_array.getJSONObject(i);
                String column1= result_json_object.getString("col_name_1");
              String column2= result_json_object.getString("col_name_2");
   
                System.out.println(" column1 ::"+ column2 );
             
                }
            }
        }catch(JSONException e){
             Log.e("log_tag", "Error parsing data "+e.toString());
                
        }


Thursday, 20 September 2012

How to access a .properties file on remote server using Java

One of the simplest ways to access a .properties file on remote server is by sending a HTTP request. Similarly any other type of file can also be accessed by using the appropriate API
It can be done in the following way...


Properties prop = new Properties();

    try {
               //load a properties file
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new  HttpPost("http://hostname/xxx.properties");
    HttpResponse response =   httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    prop.load(is);

    //get the property value and print it out
    System.out.println(prop.getProperty("url"));
   
    } catch (IOException ex) {
    ex.printStackTrace();
        }

    }

Monday, 3 September 2012

Fix for Exception in thread "main" java.lang.NoClassDefFoundError: org/json/JSONException

Problem:
Fix for Exception in thread "main" java.lang.NoClassDefFoundError: org/json/JSONException in eclipse IDE

Cause:
json jar not found in the class path

Fix:
Download json jar
www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

Select project->Build path->Add external jar->add the jar->clean and build the project

Sunday, 2 September 2012

Fix for Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/ref/FinalReference

Problem:
 Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/ref/FinalReference  occurs when we try to run a Java Application from an android project

Fix:
1.Select the project.
2.Open the run configuration .
3.New configuration->Classpath tab->under Bootstrap entries->find android library->remove it
4.Now, select bootstrap entries->click on Advanced->select Add library->click ok.
5.Select the JRE-> finish
6.Run the project now.



Tuesday, 14 August 2012

How to check the processes in use from command prompt

Many a times, while configuring the web server, we may have to configure the connection port and server port. If the port is already in use then we get error.

The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).


To fix this, we need to find the running process in that particular port.
1. Type netstat -ao in the command window. This is will show the port and PID in use.
2. Check the task manager, for the respective PID. This shows the program blocking the port. You may then decide if it is better to stop the program or change the port number...

Monday, 6 August 2012

Java annotations

Java programming language has built in annotations which helps us to add  or put some metadata to our code. This metadata is to provide some information on the classes, methods, variables or packages.

Annotations , which may be applied to the code are as follows:

1.@override:

This annotation is applied to a function to see if its been over ridden correctly,to that of that of its parent class  function. A compiler error is thrown, if the method is not over ridden as that of its super class(not immediate though.any one of the super class).

For example.,

public class Baseclass{

public void test(){

System.out.println("do stuff");

}



}

class Derivedclass extends Baseclass

{

@Override

public void Test() //compiler error..
{
}
}

Here the compiler would expect the name of Test() of Derivedclass to match that of the test() in Baseclass.Code will compile if its changed to test().By this annotation , compiler ensures that we have over ridden the method correctly avoiding any typing errors.


2.@deprecated:

Some times there might be a function written with more powerful feature than the existing one. As most of the people might have used the older one, to give them time to accommodate new change as well as to avoid using it again and warn the developer that the function may be removed anytime in future, methods are deprecated.

@deprecated is a built in annotation used to let the developer know, they are using a deprecated method.

Example:
public class Annotatefunction {
public static void main(String[] args) {
Derivedclass dc = new Derivedclass();
String result = dc.test(); // test is shown as deprecated though    no error is thrown
}
}
class Derivedclass extends Annotatefunction
{
@Deprecated
public String test()
{
return "";

}
}

3. @SuppressWarnings :
Here is a simple example to show the usage of SupressedWarning..
As the name says, it is used to suppress any of the warning messages thrown by the compiler.

For example.,
public class Annotatefunction {
public static void main(String[] args) {
Derivedclass dc = new Derivedclass(); //IDE shows warning that value of the local variable is not used.
}
}
class Derivedclass extends Annotatefunction
{
@Deprecated
public String test()
{
System.out.println("hi");
return "true";
}
}



Introducing this annotation for the main method., the warning could be suppressed.

@SuppressWarnings("unused")
public static void main(String[] args) {
Derivedclass dc = new Derivedclass(); //no warning is thrown now
}

For the list of parameters used for suppresswarnings, please refer to the eclipse documentation.
at ECLIPSE document site.

For quicker reference, i have pasted the content from above website...

allDeadCodedead code including trivial if(DEBUG) check
allDeprecationdeprecation even inside deprecated code
allJavadocinvalid or missing javadoc
assertIdentifieroccurrence of assert used as identifier
boxingautoboxing conversion
charConcatwhen a char array is used in a string concatenation without being converted explicitly to a string
compareIdenticalcomparing identical expressions
conditionAssignpossible accidental boolean assignment
constructorNamemethod with constructor name
deadCodedead code excluding trivial if (DEBUG) check
dep-annmissing @Deprecated annotation
deprecationusage of deprecated type or member outside deprecated code
discourageduse of types matching a discouraged access rule
emptyBlockundocumented empty block
enumIdentifieroccurrence of enum used as identifier
enumSwitchincomplete enum switch
fallthroughpossible fall-through case
fieldHidingfield hiding another variable
finalBoundtype parameter with final bound
finallyfinally block not completing normally
forbiddenuse of types matching a forbidden access rule
hashCodemissing hashCode() method when overriding equals()
hidingmacro for fieldHiding, localHiding, typeHiding and maskedCatchBlock
indirectStaticindirect reference to static member
intfAnnotationannotation type used as super interface
intfNonInheritedinterface non-inherited method compatibility
intfRedundantfind redundant superinterfaces
javadocinvalid javadoc
localHidinglocal variable hiding another variable
maskedCatchBlockhidden catch block
nlsnon-nls string literals (lacking of tags //$NON-NLS-<n>)
noEffectAssignassignment with no effect
nullpotential missing or redundant null check
nullDereferencemissing null check
over-annmissing @Override annotation
paramAssignassignment to a parameter
pkgDefaultMethodattempt to override package-default method
rawusage a of raw type (instead of a parametrized type)
semicolonunnecessary semicolon or empty statement
serialmissing serialVersionUID
specialParamHidingconstructor or setter parameter hiding another field
static-accessmacro for indirectStatic and staticReceiver
staticReceiverif a non static receiver is used to get a static field or call a static method
superoverriding a method without making a super invocation
suppressenable @SuppressWarnings
syncOverridemissing synchronized in synchronized method override
syntheticAccesswhen performing synthetic access for innerclass
tasksenable support for tasks tags in source code
typeHidingtype parameter hiding another type
uncheckedunchecked type operation
unnecessaryElseunnecessary else clause
unqualifiedFieldunqualified reference to field
unusedmacro for unusedArgument, unusedImport, unusedLabel, unusedLocal, unusedPrivate and unusedThrown
unusedArgumentunused method argument
unusedImportunused import reference
unusedLabelunused label
unusedLocalunused local variable
unusedPrivateunused private member declaration
unusedThrownunused declared thrown exception
unusedTypeArgsunused type arguments for method
uselessTypeCheckunnecessary cast/instanceof operation
varargsCastvarargs argument need explicit cast
warningTokenunhandled warning token in @SuppressWarnings

4.@Retention:
We can build our own annotations like we declare an interface.
This is how it is done.

Example:

@interface MyFirstAnnotation
{
String method1();
String method2();
}


@Retention are meta annotations and this with its enumerated constants tells how long the annotation has to be retained.
It has three constants. 

1. RetentionPolicy.CLASS
2.  RetentionPolicy.SOURCe
3.  RetentionPolicy.RUNTIME


Default value is RetentionPolicy.CLASS. i.e. If there is no retention policy specified for the annotation then by default it applies the CLASS one.RetentionPolicy.CLASS will store the annotation in class file, but is not available in runtime for any external tool or api(like java refelection) to access.
RetentionPolicy.Runtime will store the annotation in class file and is available in runtime for accessing.
RetentionPolicy.Source will not store the annotation in class file.

Example of how to use the retention annotation on the above code snippet.

@Retention(RetentionPolicy.SOURCE)
@interface MyFirstAnnotation
{
String method1();
String method2();
}

@ symbol before interface says that it is an annotation.




Sunday, 29 July 2012

String objects are immutable



String is one of the most important classes in Java API.String objects are immutable. It means that once an object is created it cannot be modified.Immutable objects are automatically thread safe/synchronized.Apart from String class, all the other Wrapper classes like Integer,Boolean,Character,Byte.., etc are also Immutable.

A string object can be created either by using new operator or  by using sting literals.

String txt1 = "Text1";
// this creates an object with value "Text1" and assigns to txt1 in the string constant pool.(String constant pool is maintained by the JVM, for memory management.This way it looks for the string constant pool to find out if there is already an object with the same value, if so, it makes this reference to point to the same object instead of creating another object).

eg., if there had been another object created like this before
String txt2 = "Text1";
then String txt1 = "Text1"; will merely assign the txt1 reference variable to "Text1" object.This way there may be a lot of references pointing to the same object. If some other program is allowed to modify the object, then there might be problems for the other references.This is the reason why String objects have been made immutable. 

String txt1 = new String("Text1");
//this creates a new object with value "Text1" and assigns to txt1 in the heap.

To check the above, we can use the == operator and .equals() method.

== operator checks if the references are pointing to same object.
.equals() checks if the values are same in both the objects.

Code:
public class CheckString {
public static void main(String[] args) {
String txt1 = new String("Text1"); //object created in heap
String txt2 = "Text1"; // created in string constant pool
if(txt1 == txt2)
{
System.out.println("txt1 and txt2 references points to same  object");
 }
if(txt1.equals(txt2))
System.out.println("values are same for both txt1 and txt2");
 String txt3 = "Text1" ; // in String constant pool as already       there is "Text1" object, txt3 is made to point to it instead of     creating new one.
 if(txt2 == txt3)
   System.out.println("txt2 and txt3 points to same object");
 if(txt2.equals(txt3))
   System.out.println("txt2 and txt3 values are equal");     
 }
 }

Solution:

values are same for both txt1 and txt2
txt2 and txt3 points to same object
txt2 and txt3 values are equal


Java Heap Space:
Java's Heap space is the memory what JVM borrows from operating system and allocates for our program.Every object created with new operator is stored in this heap space.Most of the unused objects are garbage collected. But, some times we do encounter,  java.lang.OutofMemory error in our webserver console.To solve this, we can increase the heap size by overriding the -Xms and -Xmx parameters. It mentions the minimum and maximum memory size respectively.Restart the web server and the error goes away..

java -Xms<initial size> -Xmx<maximum size> program_name
eg., java -Xms64m -Xmx128m CheckApp
However if the heap size is set greater than our computer's physical memory, it leads to some error like

Error occurred during the initialization of the JVM.
Could not reserve enough space for object heap
could not create the Java virtual machine.


Solution:
Reduce the heap size lesser than the physical memory.


If the outofMemory does not go away , then we may have a memory leak. Memory leak is nothing but we have an object existing in the memory without reference, which will never be used again and it does not get garbage collected.





Wednesday, 25 July 2012

Access Modifiers in Java

Access modifiers helps to restrict the access of our class by other programs.
Even though we don't specify any access modifier, implicitly it has default access.


public, protected and private are the keywords used in access control.


public: By marking a class , method or variable as public , it can be accessed from anywhere irrespective of the packages.However ,though it is public, to use a class residing in some other package , we have to import it in our class.


A class can be marked only as public or default.

A java file is named with the name of the class. If there are more than one class in the java file , then the source file should be named with the class marked as public and this class should have the main method implemented. There cannot be more than one public class in a java source file.If no class is marked public, then the one with main method should be used as the source file(.java) name.


protected: By marking a method or variable as protected, it can be accessed within the class as well its subclass irrespective of the package.It cannot be accessed if there is no inheritance.


default: If there is no access specified then, implicitly compiler applies default access to it.Like other key words, we cannot explicitly specify this modifier.In this case, the class, method or variables are accessible within the class and even from some other class, but within the same package.


private: By marking a method or variable as private, its access is restricted to its class. Nothing from outside the class can access it.










Thursday, 19 July 2012

Java Program execution - a deeper look.




Java Compiler - javac..


javac is the java compiler used to compile the java program. It is included in the Java Development Kit(JDK). It is responsible to convert the java  source code to bytecode adhering to the specifications of the Java Virtual Machine(JVM).

JVM..
It is the JVM, who interprets or runs the byte code.
JVM is distributed with the dynamically loadable libraries(reusable functions) used by most of the operating systems. These Java Class libraries internally implements the JAVA API. JVM together with these API forms the JRE.
JVMs implementation differs across various operating systems.JVM has a Just in Time(JIT) compiler within it which can interpret the bytecode and convert it into the Machine code during the run time.

Java is platform independent...
As the byte code is created here during the compilation, it can be used in any platform installed with the JVM specific to its operating system. Hence Java is referred to as platform independent language. (However JVM s implementation are platform dependent). A .class file created in one platform can be executed in any other platform.


When a Java interpreter runs a java program, the execution begins with main method. 


public static void main(String args[])


public: This is to ensure that this particular method can be accessed from any where. Marking it private will restrict its access to the particular class.So Java interpreter cannot access it.Hence it has been designed to be public.Other access specifiers are protected and default.

static: By marking a method with static keyword, we need not create an object to access the method. Here when a class file is executed by java interpreter, it has the  name of the class file.
So the main method is invoked by _class_file_name.main()...
If it is not marked static then object should be created to call the method. As all this happens even before object creation , it is designed to be static.


void: Return type has to be void.Our function need not return any thing here.Unlike C++, in Java the program may not terminate when the main method ends.It just begins from main() and in many multi threaded environments, there are other threads running to accomplish the task. Hence, it is too early to return an exit code or in many cases it does not make any sense.So in case we need to return anything like an error code , System.exist() is used for the same.


main: Java interpreter calls the main method . It cannot be of any other name.It is also case sensitive. Method main takes in the argument String args[].It can accept an array of String arguments as command line arguments. args is just a variable name . Any name...eg. abb, azx..are valid.




In the below code , the compilation creates a Hello.class file.Interpreter invokes the main method by calling Hello.main().


package com;
/*
 * Class Hello
 */
public class Hello {
/*
* Method main
* prints the text "Hello"
* execution starts from main method
*/

public static void main(String[] args) {
System.out.println("Hello"); //this statement prints "Hello"
}


}





Sunday, 15 July 2012

Requisites to run a Java Program

To compile and run a java program , we need the following


2.Install the jdk and Jre by running the set up.

2. An IDE(We use eclipse here. Please download Eclipse IDE for Java EE Developers from http://www.eclipse.org/downloads/)

Setting Environment Variables:

We  should set the environment variables in order to successfully execute our java program.

In Windows Operating system,

1.Right click Computer ->Properties ->Advanced Systems settings->Advanced ->Environmental Variables

2.Click on New. 

  •  Variable name should be PATH 
            Should point to the path of bin folder of the jdk folder installed. 

        Click on OK to save this.

  •  Add another environment variable by clicking on new . Variable name :CLASSPATH 
              
This should point to the lib folder of the JRE installed. Click on OK to save this.



  • Add another variable JAVA_HOME. This should point to the JRE Folder installed.
                  
                                       


      Click on OK to save this.


  •       Download the eclipse zip folder  and extract the same to a folder. Run the eclipse.exe file.
  •       Create a new folder and use the same as workspace.
  •       To create a new java project. Click on File -> New -> Java Project
  •       Enter the name of the project, click on OK to continue.
  •       Once the project has been created, right click on the same to create a new Java class. New-> class.(Eg. Hello)
Sample code to test the setup:

public class Hello {
public static void main(String[] args) {
System.out.println("hello");
}

}

Right click on the code as shown below and and Run the code by clicking on Run as ->Java Application



This will print hello in the console.

Thanks for your time...


Thursday, 12 July 2012

Multiple Inheritance in Java::Diamond Problem



What is Multiple Inheritance???
Multiple Inheritance is a concept  which allows a subclass to inherit from more than one super class.

Unlike C++ , Java does not support multiple inheritance by extending more than one superclass.

Why so????

We have Classes B & C extending Class A ...



If another Class D is allowed to extend Class B as well as Class C...



and if doWork() method is overridden both in Class B as well as Class C

From Class D, it becomes ambiguous to invoke doWork() as it had inherited two different implementations for the same.

The class hierarchy forms a diamond shape when represented by diagram and hence got its name "THE DIAMOND PROBLEM"

This problem is however solved by using Multiple Interface Inheritance..Which we will learn when we read about Interfaces..As of now we have a understanding of why multiple inheritance is not supported by JAVA..by extending more than one super class..





Thursday, 28 June 2012

OOPs concept with Examples

For us to learn the Java technology, we need to have  a clear understanding of Object oriented concepts.

As we may  have heard many times,  C++ , Java, ...are all object oriented programs. What does this actually mean? . In  Java world, everything is considered as an object. By making your program object oriented , you considerably increase the chance of re-usability and modularity of the code. Does it not sound great that a code written by you was found more generic and could be reused in many instances just by invoking your object created.  We could possibly define any real world object with the two characteristics like state and behavior.

Lets us understand the STATE and BEHAVIOR with an illustration:

I have a pet dog at home. He is a german sheperd breed , He is brown in color. He does play with a ball , he does accompany me for a walk, he does greet friends by wagging his tails.
So here the STATE can be categorized by common characteristics of a dog like , "BREED,COLOR,GENDER"

BEHAVIOR will be WALKING,GREETING and PLAYING

so now are you able to relate what it means a STATE and BEHAVIOR.
 
In java terms, now Class will become Dog, all the STATES (color,breed,gender) will become variables and  the BEHAVIORS , "walking , greeting, playing " will become  methods.

In Java words ,

class Doggie
{
string name;
string color;
string  gender;

void doPlay()
{

}

void doGreet()
{

}

void doWalk()
{

}

}


So we are now able to relate a real world object to a software object..

Lets continue with the OOPs concepts like Encapsulation, Inheritance , polymorphism, Abstraction in the next blog.