Friday, May 3, 2013

Adding a Foursquare, Google+ like sliding drawer to your android app


Currently Android SDK does not support such a feature. But this kind of designs are very popular between the users. But there are many open source libraries which facilitates sch omplementation. https://github.com/jfeinstein10/SlidingMenu is an open sorce sliding drawer library which is used many poplar android applications. Using this is prettry simple. This video explains how to integrate with your android project. After the integration is done you can create a sliding drawer like this.

Add the following code to onCreate() method of your activity.

    menu = new SlidingMenu(this);
    menu.setMode(SlidingMenu.LEFT);
    menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
    menu.setShadowWidth(5);
    menu.setFadeDegree(0.0f);
    menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
    menu.setBehindWidth(150); //change width according to your device
    menu.setMenu(R.layout.menu_frame);

Here menu_frame is the layout of the sliding drawer. It has to be a frame layout and you can add any other layout to the frame layout.

If your application has a actionbar you may need to link sliding drawer to the app icon like in Google+ and Youtube Android applications. What is usually happen is toggling the sliding drawer when the app icon is clicked. It can be implemented like this.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
       case android.R.id.home:
               menu.toggle();
               return true;
   }
   return true;
 }



Wednesday, November 28, 2012

Create new Java Class files at runtime

When we write programs usual method is to write all the code compile it and run. But when we try to complex things some times we may want to generate a new class and use it at runtime. As an example I wanted to create a class which parse a xml message and create a new Java object from that data. This is used in web server. So that result object varies according to the web service which is deployed. The solution was to inspect the service at deployment time and create a new parser class according to that in the service deployment time. It has to be noted that this parser had to be generated as a .class file and dynamically added to the classpath. So the result was to use a bytecode manupulation library. There are few bytecode manuplulation libraries available as ASM and JavaAssist.
I used JavaAssist for this. The reason for using JavaAssist is it is simple to create a new class from the scratch using JavaAssit. When we create new class files using JavaAssit we have to create all the methods in the new class as Strings and the pass them to Java Assist. As a example if we have to add amethod called sayHellow() to new class we can create it as a String like this.
String s="public void sayHello(){ System.out.println("Hello"); }

/**
     * @param c   Any class which can be used to get the class loader                          (c.getClassLoarder()) can be passed using object.getClass() methood
     * @param name
     *            Name of the to be generated class
     * @param methods
     *            Methods to be created as Strings
     * @param interfaces
     *            interfaces to be implemented as Strings
     * @param directory
     *            the directory generated class files has to be written
     */
    public static void createClass(Class<?> c, String name, List<String> methods,
            List<String> interfaces, String directory) {
        String temp = null;
        try {
            ClassPool pool = ClassPool.getDefault();
            pool.insertClassPath(new ClassClassPath(c));
            CtClass cc = pool.makeClass(name);
            if (interfaces != null) {
                for (String s : interfaces) {
                    CtClass anInterface = pool.get(s);
                    cc.addInterface(anInterface);
                }
            }
            for (String s : methods) {
                temp = s;
                CtMethod m = CtNewMethod.make(s, cc);
                cc.addMethod(m);
            }
            cc.writeFile(directory);
        } catch (Exception e) {
            // TODO throw
            System.out.println(temp);
            e.printStackTrace();
        }
    }

To add this class to the classpath following method can be used.

//Here directory is the path which class files were written

 public static Class loadClass(String className,String directory, ClassLoader loader) throws Exception {
        File f = new File(directory);
        java.net.URL[] urls = new java.net.URL[] { f.toURI().toURL() };
        ClassLoader cl = new URLClassLoader(urls, loader);
        Class cls = cl.loadClass(className);
        return cls;
    }

Note - JavaAssist does not support generics. If we use genarics java assist throws an exception. We have to use fully qualified names for types. As an example we have to use java.util.List for List type.

Monday, October 8, 2012

How to get the base class of a Array using java reflection.

If we use Java reflection to get the class of a object like String[][] strings; Java reflection will return [[Ljava.lang.String. But sometimes you may want to get the bases class e.g in this case java.lang.String. Following method can be used to do that. If you want to get the bass class of array object a you use this as Class c=getTypeOfArray(a.getClass());

public static Class getTypeOfArray(Class c){
        Class cls=null;
        while(true){
            if(c.isArray()){
                c=c.getComponentType();
            }else{
                cls=c;
                break;
            }
        }
        return cls;
    }

Monday, September 3, 2012

GSoC 2012 with Apache Photark, A great experience.



Google summer of code is one of the worlds leading opensource development programs. It is held anually by Google inc. Many enthusiastic students participate each year for this.
In every year many number of students try to take part of this program. But nearly 1000 students only get selected for this event.  I was lucky to take part in 2012 program for the first time.
I took part on GSoC 2012 under Apache Software Foundation for their incubator project Photark.

The interesting thing was my initial plan was to participate on another organization which develops a CMS. I also worked with them nearly one month. But then I realized what they are expecting and what I am interested is not matching. So I looked for another organization and found this interesting project.
But then there was little time for application closing period.  So I quickly checcout the code base play with it for little time, drafted a proposal and submitted it.
Then Mr. Suhothayan Sriskandarajah who was happened to my mentor contacted me and explained further about what they are expecting and pointed out week points in my proposal. Then I updated my proposal according to the feedbacks. Then I started familiarizing with other technologies were new to me but need for this project.
Time went results came. Boom, I was taking part in GSoC 2012. Then the community bonding period started. But there was a slight problem I had exams in first two weeks of the community bonding period. But the community was very friendly. They understood my situation and they give me freedom until exams are over.
Then I started cording. Since it was a somewhat green field project (project details will be explained in another blog post) I had to take important design descisions how the UI must be organized, what are the libraries to be used, etc. But I managed to done it in to a significant level when the mid evaluation came.
In the mid evaluation my mentor evaluated my problem and we discussed what have to be done in the next half. Also my mentor suggested some UI improvements which were essential to make the app usable.
Mean time the community decided to give me the commitership for the project. They asked whether I like to be a committer and I agreed instantly. After the normal procedures (signing the ILCA etc.) I officially became a committer at Apache Photark. This helped me to contribute to the project more efficiently. Not I could do the changes immediately without submitting patches waiting until they applied. Also I could quickly do bug fixes.
After the mid term evaluation as the first task I did the UI improvements and gave id a modern and user friendly look and feel. Then I implemented rest of the  functionality gradually. When It comes to the final evaluations I have completed most of the planned functionality as they were planned. The app has came to a release level with my contributions and other GSoC participant's contributions. 
Then I did a code review with my mentor and he suggested some changes to code structure and naming    conventions to make it more understandable and clean. It is very important for a open source project since many people are going to contribute it in the future. After the soft pencil down date we did an another code review and officially ended out mentoring sessions for GSoC 2012.
After the evaluation period I was officially notified that I have completed GSoC 2012 successfully. Finally I like to say GSoC 2012 was one of the best experiences in my life. It gave me the opportunity to involve with open source projects, communities and contribute to them. Those contributions will not be limited to the GSoC period and I am going to do those contributions further.  
Finally I like to thank the people who helped me to make this project a success. First of all I like to thank my mentor who gave me this amazing opportunity and helped me throughout this project. Also I like to thank the project lead Luciano Resende, project member Avdesh Yadav and other GSoC participant Bhargav for their help throughout this project. I will discuss about my project in the next blog post in detail. 

Sunday, August 12, 2012

How to get current time and date using JavaScript.

Getting system date and time using JavaScript is easy. But some steps has to follow to convert it to a readable format. These functions will help you to get rid of the hassle .

//returns date in format 01/01/2012

function getCurrentDate() {
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
return (month + "/" + day + "/" + year);
}

//returns time in format 05:45 AM
function getCurrentTime() {
var time = ""; var currentTime = new Date(); var hours = currentTime.getHours(); var minutes = currentTime.getMinutes(); if (minutes < 10) { minutes = "0" + minutes; } var h; if (hours > 12) { h = hours - 12; } if (h < 10) { h = '0' + h; } time += (h + ":" + minutes + " "); if (hours > 11) { time += ("PM"); } else { time += ("AM"); } return time;
}

Thursday, June 28, 2012

How to build a maven project without tests

When we build a large project using maven it takes a lot of time because of tests  runs. So we can build quickly by disabling the tests. We can do that using the following command.
mvn -Dmaven.test.skip=true install

Wednesday, May 30, 2012

Using Geolocation API in phone gap

I am currently developing a Phonegap application for Google summer of Code 2012. I encountered some problems when using it and this is how I corrected them.

Location not available- In android emulator does not automatically get the location. So we have to send a moc location to the emulator using DDMS perspective in eclipse.

Phonegap documentation says to use the below method to get location.

navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError);

But this gave me an error with error code 2 unable to start geolocation service. I corrected it using the below method.

navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError,{ enableHighAccuracy: true });

Note - This is only for testing in the emulator.