Skip to content


View core Android Java sources in Eclipse (final solution)

I don’t know why this is not really showing in Google search results but if you want to step through the core Android Java code in your Eclipse project, finally there’s a legit and very convenient solution that is a part of ADT-Addons project. Steps are pretty self-explanatory but just in case,  here’s what you need to do:

  1. In your Eclipse click Help->Install New Software
  2. Click “Add” button and put this URL into resulting Pop-up (name it whatever you want): http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/
  3. Click “OK” and mark “Android Sources” checkbox
  4. Click “Next” and any “OK”, “Agree”, “Next” or “Finish” buttons afterwards
  5. Restart Eclipse after the installation and now you can step right into Android code from your debugger and see the source code for Android Java files right in the Eclipse editor

Posted in Android, Programming.


Free some space on your Android phone

If you have had your Android phone for a while it is very possible that just like me you are suffering from its unbelievably small and ever shrinking memory. You probably have no space to install any new apps and don’t want to give up any of ones you have. So here are few tips that hopefully will help you to free few megs of the precious internal mem! As a note – this will not go into weird and difficult solutions such as cache management apps and rooting your phone, for that you can go to XDA forums

For the lawyers out there: use these tips at your own risk. I do and I’m yet to brick my phone or to lose any valuable information but that is not to say that you may not.

General requirement

Before doing anything described below make sure that your phone settings and information is backed up. Go to Phone->Settings->Privacy and make sure that “Back up my data” and “Automatic restore” options are checked. Otherwise you are at risk to lose valuable data on your phone permanently

G+ &Co

gplus This “new kid on the block” uses internal memory very liberally (slap, slap, slap). I found out that periodically it helps to go phone->settings->Applications->Manage Applications, locate G+ app and click on “Clear data” button. Yes, it will give you a stiff warning saying that your phone will melt and the boogie man will comeandgetcha but I found that it really has no adverse effect except I’d have to log back in.

Other apps in this category (save to Clear data) are Browser and Market and you may find more but be careful. All the apps I mentioned are backed by Google servers, when you delete data it is replaced by a new set. On the exclusively phone-based apps you will lose all your settings and modifications

Get rid of unwanted apps (kind of)

No I’m not telling you to delete that “Busty blonds” app that you not using (are you?).  As I said – if you’re like me you are not giving anything up. But there is number of unused “default” apps that come with your phone. Unfortunately you cannot delete these apps easily but if you were updating these (especially automatically) and want to regain some space do the following:

Locate the app in the same settings area as above. Do “Clear cache”, “Clear Data” and then click on “Uninstall updates”. As a very minimum the app will shrink to half of its size. Latest app on my NexusOne to go this way was Facebook (I’m a bit proud of it)

Scary stuff or nuke your contacts

I know this is a dangerous proposition but let me give you some background. When you got your new phone it was initially populated with your Google contact list. Any modifications or additions from your phone are also synchronized back to Google servers. So about 1 year and change ago it become fashionable for 3rd party apps to synchronize their contacts to your phone also. Fortunately, Android does not combine accounts internally but keeps them separate and only unites these on your screen. If you’ve been syncing and trying things like Facebook, Twitter, Linkedin and our own Droidin you probably have tons of strange contacts that make no sense and by the way steal your precious memory.

I also found out that even when removed or disabled from settings->Accounts & sync just adding and removing and syncing leaves a lot of residue behind.

So gather your courage and locate the app called “Contacts Storage” and do the same “Clear data” trick. After that access your contacts and be horrified, you will see nothing there. However in a short while your missing contact information will be pooled from Google. Stiff warning: you will lose your call log and “Frequently called” section so don’t say I didn’t warn you. I gained about 10Mb with this trick so if you are very desperate you may consider this.

Start anew

This one is really dumb: say by-by to all the customization, pull out SD card and do factory reset. How? Phone->Settings->Privacy->Factory data reset. This will pretty much wipe out everything on your phone to a clean slate.

Then you can recall that sweet feeling you had 2 years ago when you first logged in into you brand new super-phone

If you have purchased any paid applications you will be able to add these back with no charge by going to Market and locating the app. Instead of “Purshase” button you will see “Install”

Hope this helps and Ho, ho, ho – Merry Christmas and a Happy New Year!

Posted in Android, non-programming.


Android: display orientation in phones vs tablets

If you have 2 layouts (portrait and landscape) and the order seems to be reversed on the tablet then switch to using getRotation instead of deprecated getOrientation. Something like this

    private void setLayout() {
        // Get display for detecting the phone orientation
        final Display display = ((WindowManager) getSystemService(
            WINDOW_SERVICE)).getDefaultDisplay();
        if (display.getRotation() == Surface.ROTATION_0 ||
            display.getRotation() == Surface.ROTATION_180) {
            setContentView(R.layout.home);
        } else {
            setContentView(R.layout.home_l);
        }
    }

P.S.
Actually, ignore code above it will not work. All you really need to do is to detect what is larger – height or width and adjust layout accordingly

    private void setLayout() {
        // Get display for detecting the phone orientation
        final Display display = ((WindowManager)
             getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        final boolean isTall = display.getHeight() > display.getWidth();
        setContentView(isTall ? R.layout.home : R.layout.home_l);
    }

Posted in Android, Java, Programming.


Replace black (grey) with color (colorize) in Photoshop

I just spent some time making black (grey scaled) icon into a blue one and here’s by far the easiest way to do it in the Photoshop:

  • Open the original image and change mode to RGB (Image->Mode->RGB)
  • Image->Adjustments->Hue/Saturation
  • Click on “Colorize” checkbox
  • At this point the image will still be black and white (grey)
  • Make sure that “preview” box is checked
  • Start by increasing “Lightness” you will immediately see color changing from b/w to blue
  • Play with other 2 dials (hue & saturation) to get you to the desired color

Posted in Web stuff, non-programming.


Use Yaml with Spring to load properties

I was surprised to find that Spring framework doesn’t have Yaml-based PropertyPlaceholderConfigurer to load nested properties from Yaml property file. After some investigation turned out that instead of writing YamlPropertyPlaceholderConfigurer it is sufficient to write Yaml implementation of PropertiesPersister.

Here’ show your applicationContext.xml (snippet) will look

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:///C:/foo/properties.yaml</value>
        </property>
        <property name="propertiesPersister" ref="persister"></property>
    </bean>
    <bean id="persister" class="com.foo.utils.YamlPropertiesPersister"></bean>

And here’s bare-bone PropertiesPersister implementation using SnakeYaml as parser

public class YamlPropertiesPersister implements PropertiesPersister {
    @Override
    public void load(Properties props, InputStream is) throws IOException {
        load(props, new InputStreamReader(is));
    }

    /**
     * We want to traverse map representing Yaml object and each time we will find String:String value pair we want to
     * save it as Property. As we are going deeper into map we generate a compound key as path-like String
     *
     * @param props
     * @param reader
     * @throws IOException
     * @see org.springframework.util.PropertiesPersister#load(java.util.Properties, java.io.Reader)
     */
    @Override
    public void load(Properties props, Reader reader) throws IOException {
        Yaml yaml = CollectorUtils.instanceOfYaml();
        Map<String, Object> map = (Map<String, Object>) yaml.load(reader);
        // now we can populate supplied props
        assignProperties(props, map, null);
    }

    /**
     * @param props
     * @param map
     */
    public void assignProperties(Properties props, Map<String, Object> map, String path) {
        for (Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            if (StringUtils.isNotEmpty(path))
                key = path + "." + key;
            Object val = entry.getValue();
            if (val instanceof String) {
                // see if we need to create a compound key
                props.put(key, val);
            } else if (val instanceof Map) {
                assignProperties(props, (Map<String, Object>) val, key);
            }
        }
    }

    @Override
    public void store(Properties props, OutputStream os, String header) throws IOException {
        throw new NotImplementedException("Current implementation is a read-only");
    }

    @Override
    public void store(Properties props, Writer writer, String header) throws IOException {
        throw new NotImplementedException("Current implementation is a read-only");
    }

    @Override
    public void loadFromXml(Properties props, InputStream is) throws IOException {
        throw new NotImplementedException("Use DefaultPropertiesPersister if you want to read/write XML");
    }

    @Override
    public void storeToXml(Properties props, OutputStream os, String header) throws IOException {
        throw new NotImplementedException("Use DefaultPropertiesPersister if you want to load/store to XML");
    }

    @Override
    public void storeToXml(Properties props, OutputStream os, String header, String encoding) throws IOException {
        throw new NotImplementedException("Use DefaultPropertiesPersister if you want to read/write XML");
    }
}

And as an added bonus, here’s how you create Yaml instance with SnakeYaml

    public static Yaml instanceOfYaml() {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED);
        final Yaml yaml = new Yaml(new Loader(), new Dumper(options), new Resolver() {
            /**
             * @see org.yaml.snakeyaml.resolver.Resolver#addImplicitResolvers()
             */
            @Override
            protected void addImplicitResolvers() {
                addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO");
                // disable resolving of floats and integers
                // addImplicitResolver(Tags.FLOAT, FLOAT, "-+0123456789.");
                // addImplicitResolver(Tag.INT, INT, "-+0123456789");
                addImplicitResolver(Tag.MERGE, MERGE, "<");
                addImplicitResolver(Tag.NULL, NULL, "~nN\0");
                addImplicitResolver(Tag.NULL, EMPTY, null);
                addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, "0123456789");
                addImplicitResolver(Tag.VALUE, VALUE, "=");
            }
        });
        return yaml;
    }

Posted in Java.


Python Pygments in Java with Jython

I was looking for the good code-highlighting package to use in my Java (GWT) project and after much research selected Pygments. It took me a while to figure out how to make all different parts work happily together so here’s a tutorial on how to do it.

Jython setup

To run Pygments you need to add Jython.jar to the list of your libraries. I’m using release 2.5.1 at the time of writing. First and foremost – using barebone distribution such as found in Maven repo or in the Jython distro is not sufficient. I tried many ways to setup and the only way that worked is to

  1. Uncompress jython.jar in some temp directory
  2. Add Jython/Lib directory to the top
  3. Add Pygments Python files to the top
  4. Jar everything back again and add resulting archive to your project. I called it jython-full.jar
  5. No matter what you are using this jar has to be on your classpath

Code

Highlighter.py

Create custom highlighter.py file and place it to your resources or even Java files as long as it gets placed in the top level of your classpath. In my case I’m using Eclipse/Maven so I placed this file into src/main/python and added that folder as a source folder. Here’s complete code for highlighter.py:

from reporting.python import Highlighter
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

class PyHighlighter(Highlighter):
    def __init__(self, lexername):
        self.lexer = get_lexer_by_name(lexername, stripall=True)
        self.formatter = HtmlFormatter(linenos=True, cssclass="source")
    def colorize(self, code):
        return highlight(code, self.lexer, self.formatter)

Highlighter.java

Highlighter.java is interface that your Java code will be using to communicate with Pygments.

package reporting.python;

public interface Highlighter {
    String colorize(String rawText);
}

HighlighterFactory.java

HighlighterFactory is Java class that creates instances of Highlighter object. It’s given here in barebone form and can be greatly optimized by converting to a singleton and cashing particular instances of Highlighter for further reuse. But it will work as given:

package reporting.python;

import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;

public class HighlighterFactory {
    private PyObject matrix;

    public HighlighterFactory() {
        PythonInterpreter pi = new PythonInterpreter();
        pi.exec("import sys");
        // makes Jython able to find your custom Python code
        pi.exec("sys.path.append('WEB-INF/classes')");
        pi.exec("from highlighter import PyHighlighter");
        matrix = pi.get("PyHighlighter");
    }

    public Highlighter create(String type) {
        final PyObject instance = matrix.__call__(new PyString(type));
        return (Highlighter) instance.__tojava__(Highlighter.class);
    }
}

Putting it all together

After creating/placing all these parts here’s code example on how to use it

    public String colorize(String text, String type) {
        HighlighterFactory factory = new HighlighterFactory();
        Highlighter highlighter = factory.create(type);
        return highlighter.colorize(text);
    }

References

Good luck and let me know if it worked for you

Posted in Programming.


iOS vs Android

Blah, blah… I’m a simple guy. I keep hearing about hackers that make iPhone run Android, I’m yet to hear about Nexus One running iOS. Why? Because no self-respecting hacker would attempt such pointless exercise

Posted in Android, non-programming.


DroidIn 2 is back!

The DroidIn – first ever LinkedIn Android client is back. In version 2 it is a complete rewrite with all new features, design and implementation. If you have Android phone (or device) please give it a try.

The details

Posted in Web stuff.


HireADroid adds Beyond.com

My pet project HireADroid adds Beyond.com support in its 2.4.0 release. HireADroid as Android job search application that now supports 5 major search engines. You can give it a try by searching for it on Android market or going to http://hireadroid.com. One query will give 5 sets of results in one neat package

Posted in Android.


Android – prevent Dialog to be cashed in the Activity

If you override Activity#onCreateDialog method to create a pop-up dialog something that you have to be aware is this dialog will be cashed for any subsequent calls. For most cases it is just the right behavior but what if you want to change contents of the dialog on the next call? One possible scenario – say you have few tabs that display similar content in the same pop-up but the info changes based on the active tab. Here’s one way to do it. When you set your onClick listener put this into onClick call:
dialog.dismiss();
activity.removeDialog(DIALOG_ID);

Here DIALOG_ID is the same ID you are using in the Activity#onCreateDialog call

Posted in Android, Programming.