Eclipse ADT : Unable to get system library for the project / Conversion to Dalvik format failed with error 1

August 14, 2011 2 comments

Google has provided the ADT plugin for Eclipse which makes the job of creating / testing android applications substantially easier that would have been if we had to use only the command line tools provided with the Android SDK. However I have been facing a strange issue repeatedly for the last couple of days. After restarting my system when I start Eclipse and navigate over to my android project, it shows error as shown in the figure below.


I had no idea as to why this happened. I opened the build path for the project and the message shown there was “Unable to get system library for the project

I tried adding the android.jar manually to the project by clicking on the “Add External Jars” button. After adding the jar and cleaning the project, the errors for java.lang.Object not found did vanish. But another problem appeared. The error was “Conversion to Dalvik format failed with error 1“. I searched the Internet forums far and wide but I guess that the error message that I received was generated a bit too often and under a wide variety of circumstances. I tried cleaning the project, restarting eclipse etc. Finally on a certain forum I found the mention of checking the .classpath file that Eclipse creates. And voila!!  the source of the problem was found !! The below listing shows the .classpath file for the project after adding the android.jar manually through the Eclipse Build Path window.

<!--?xml version="1.0" encoding="UTF-8"?--><?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="lib" path="/media/Data/Development/android-sdk-linux_86/platforms/android-8/android.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

I compared this to the entry of a new project that I created in Eclipse which was as follows.

<!--?xml version="1.0" encoding="UTF-8"?--><?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="output" path="bin"/>
</classpath>

Comparing the two, the solution was easy to identify. I replaced the third line in the .classpath file about the “lib” and replaced it with the corresponding line in the second file.

And it works now !!

As of the time of this writing I have not been able to understand why this happens everytime I restart my eclipse / system and hence I have to replace the classpath entry everytime I start Eclipse. But atleast it works. Hope this helps you. And incase it does, please share it with others.

So after starting eclipse if you see that there are problems relating to java.lang.Object not found, open the .classpath and edit the line as shown above.

Linux Command-line : Some useful Redirection techniques

Redirecting Standard Output
[me@linuxbox ~]$ ls -l /usr/bin > ls-output.txt

Append redirected output to a file instead of overwriting the file from the beginning
[me@linuxbox ~]$ ls -l /usr/bin >> ls-output.txt

Redirecting Standard Error
[me@linuxbox ~]$ ls -l /bin/usr 2> ls-error.txt

Redirecting Standard Output And Standard Error To One File
[me@linuxbox ~]$ ls -l /bin/usr > ls-output.txt 2>&1
OR
[me@linuxbox ~]$ ls -l /bin/usr &> ls-output.txt

Disposing Of Unwanted Output
[me@linuxbox ~]$ ls -l /bin/usr 2> /dev/null

How to read data from xml file on Google App Engine – Part 2

This post is in continuation to the part-1 post which can be read here.

Now we shall look at the actual parser for parsing the Data.xml file.

I have used the basic SAXParser from javax.xml.parsers and DefaultHandler from org.xml.sax.helpers. The SAXParser requires two parameters, first the xml file to be parsed and second the DefaultHandler to handle events such as document start/end, element start/end etc.

The DefaultHandler has differnt methods for the events listed above such as :

public void startDocument () throws SAXException {
	// no op
}
public void endDocument() throws SAXException {
	// no op
}

and others..

We shall override these methods our CustomXMLParser class that extends the DefaultHandler class so that we can do the specific jobs that we want.

We define the following members in the CustomXMLParser class

private String characters;
private Country tempCountry;
private String tempCountryName;
private String tempCapitalName;

//the persistence manager for saving/retrieving the data from the datastore
private PersistenceManager pm = null;

private Stack xmlObjectStack;

The characters string is used to store the vaue between the end of one tag and start of another i.e. between “>” and “<“.

The tempCountry variable stores the country object temporarirly till it gets persisted to the datastore. We shall read the different values that we require from the xml and then populate the tempCountry object with these values. After all the reuired values have beeen read (i.e. at the end of </country> tag) we shall persist this tempCountry object to the datastore.

NOTE : Please note that the class below has been written for only illustration of the basic concept and hence is in no way adhering to the best practices.

CustomXMLParser class

package com.shank.xml;

import java.io.File;
import java.io.IOException;
import java.util.Stack;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.shank.xml.demo.jdo.Country;
import com.shank.xml.demo.jdo.DatastoreUtilities;
import com.shank.xml.demo.jdo.PMF;

/**
 *
 * @author shank
 *
 */
public class CustomXMLParser extends DefaultHandler {

	//the logger for this class
	private Logger logger = Logger.getLogger(this.getClass().getName());

	private String characters;
	private Country tempCountry;
	private String tempCountryName;
	private String tempCapitalName;

	//the persistence manager for saving/retrieving the data from the datastore
	private PersistenceManager pm = null;

	private Stack xmlObjectStack;

	//constructor
	public CustomXMLParser(){
		//just initialize the stack
		xmlObjectStack = new Stack();
	}

	//the method to parse the data from Data.xml
	public void doParsing() {

		logger.info("inside doParsing()");

		if(DatastoreUtilities.checkIfEntityExists("India", Country.class)){

			logger.info("data is already present in the datastore and hence skipping the xml parsing");

		}else{
			//if the control reaches here that means that the data has not been populated in a previous request
			try {

				//get a SAXParser instance which will actually read the data from the xml
				SAXParserFactory factory = SAXParserFactory.newInstance();
				SAXParser parser = factory.newSAXParser();

				logger.info("parser created");

				parser.parse(new File("Data.xml"), this);

				logger.info("parsing done");

			} catch (ParserConfigurationException e) {

				logger.severe("!! ParserConfigurationException !!");

			} catch (SAXException e) {

				logger.severe("!! SAXException !!");

			} catch (IOException e) {

				logger.severe("!! IOException !!");
			}
		}

	}

	public void startDocument() throws SAXException {
		logger.info("inside startDocument");
	}

	public void endDocument() throws SAXException {
		logger.info("inside endDocument");
	}

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		//log the name of the element which has just started
		logger.info("inside startElement : element is "+qName);

		//check which element has started
		//we are only bothered about <country> and <capital>
		if(qName.equals("country")){
			//if control reaches here then <country> tag must have started

			//get the country name from the attributes and create a country by that name
			tempCountryName = attributes.getValue("name");
			tempCountry = new Country(tempCountryName);

			//push this country object to the stack
			xmlObjectStack.push(tempCountry);

		}else if(qName.equals("capital")){
			//if control reaches here then <capital> tag must have started

			//we do not need to do anything here as the name of the capital is between <capital> and </capital> tags

			//after here, the capital name is read in the characters() method below

		}

	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		//log the name of the element which has just ended
		logger.info("inside endElement : element is "+qName);

		//get the persistence manager instance
		pm = PMF.get().getPersistenceManager();

		//check which element has ended
		//we are only bothered about <country> and <capital>
		if(qName.equals("country")){
			//if control reaches here then <country> tag must have ended

			//pop the country object from the stack
			tempCountry = (Country)xmlObjectStack.pop();

			//this country object has already been populated fully since the country tag ends only after the capital tag has ended
			pm.makePersistent(tempCountry);

		}else if(qName.equals("capital")){
			//if control reaches here then <capital> tag must have ended

			//since the end of the capital tag has been reached, the name of the capital is already abailable in the characters variable
			tempCapitalName = characters;

			//since capital is nested within country, the country object is already present on the stack
			//get the country object from the stack and set its capital name
			tempCountry = (Country)xmlObjectStack.pop();
			tempCountry.setCapitalName(tempCapitalName);

			//push this country object back into the stack
			xmlObjectStack.push(tempCountry);
		}

		pm.close();
		pm = null;
	}

	public void characters(char ch[], int start, int length)
			throws SAXException {
		logger.info("inside characters");

		characters = new String(ch, start, length);

	}

}

Let us dissect the code of the CustomXMLParser and see how the above class is used to attain our ultimate aim.

For reference, I am listing below the Data.xml file that was already listed in the part-1 of this post.

<?xml version="1.0" encoding="utf-8"?>
<data>
	<countries>
		<country name="India">
			<capital>New Delhi</capital>
		</country>
		<country name="Japan">
			<capital>Tokyo</capital>
		</country>
	</countries>
</data>

The methods in the CustomXMLParser class that matter to us are :
startElement(), endElement() and characters()

startElement()
This method, as the name specifies, is called when the start of a tag is encountered. For instance, when the tag <country name=”India”> is encountered, this method is called and the name of the tag, i.e. “country” is passed in the qName variable and the attribute called “name” whose value is “India” is stored in an Attributes object and passed in the attributes variable. By checking the values of qName and attributes we can find out which tag we are starting with. Since we are starting with a country tag, we create a Country object and push it to the xmlObjectStack.

Using a stack helps us when we reach the end of the </capital> tag. Since the <>capital> tag is nested in the <country> tag, hence if we have reached a </capital> tag, we can be sure that we have already read the <country> tag and that the country object is available on the xmlObjectStack. We pop this country object from the stack and set its capital property to the value that is available in the “characters” string (The value of this characters string had been set by the characters() which is ready the string between > and < i.e. between the end of one tag and the start of another. Since we have reached the </capital> tag, the value of the capital (the name of the captial) is already available in the characters string. After setting the capital property of the country, we push it back into the xmlObjectStack.

When we encounter the </country> tag, we just pop the country object on the top of the xmlObjectStack and persist it to the datastore.

We repeat the same for all the countries.

Through this post I have tried to explain the basic process that we can use to read information from an xml file and do something useful from it.

Hope this helps you. And if it does, please dont forget to share it.

How to add Python 3.1 interpreter to Aptana / Eclipse Pydev ptython interpreter list

June 23, 2011 1 comment

Recently I though of starting out with Python.. The first thing I tried was to get the Python3.1 interpreter to be added to my python interpreters list in the PyDev section of my Aptana Studio 3. I could not find how to add it as I was unable to search for it.

So here I am logging it so that some one who wants to do the same can save th 10 odd minutes that I wasted while trying to figure out how to add the desired interpreter.

Go to :

Window > Preferences > PyDev > Interpreter-Python

Next click on the New button and browse to /usr/bin

Select the python3.1 file and click ok.

That adds the python interpreter to your list…

How to read data from xml file on Google App Engine – Part 1, Setup & Prerequisites

June 17, 2011 1 comment

Google App Engine is perhaps one of the best things that has happened to a small budget app developer (who dreams of making the most successful web app of the century) as far as cloud computing is concerned (IMHO). It takes a lot of complexities out of your development cycle and lets you focus on your main aim… to build that killer app !! And you dont have to worry if your web-app starts receiving hundreds of thousand of hits a day, Google App Engine would automatically scale your app for you !

But not everything is as rosy as it sounds… Google has restricted various features that would other wise be available had you chosen a normal hosting provider and a standard database. The topic of this blog entry is one such restriction – the inability to read from a file stored locally in the application..

There might be several scenarios when you may need to read data/information from an xml file stored in the application’s war. In my case I wanted to populate the datastore from the data stored in a particular xml at the application’s startup.. so that this data (which happens to be the bare minimum required for my app) is automatically populated in the datastore at startup itself. The other way was creating a form to insert this data, which actually is even more horrific idea than it sounds..

There are various parsers available for parsing xml files. I personally like the JDOM one, even though it is heavy on resources (memory). As of this moment I have been unable to use the JDOM way for parsing xml data on Google App Engine (this is because JDOM uses java IO library which does not work on the Google App Engine).

Finally I decided to write my own handler for reading the data from xml using the basix SAXParser. I shall create a sample project in order to describe how to read the xml data.

The example that I have taken assumes that you are using JDO for persistence and wish to create JDO objects and populate them with the values stored in the xml file.

The image below shows the directory structure of my demo project (XML Parsing Demo Project).

Directory Structure of Demo Project

Important Note : The App Engine considers all files inside WEB-INF as dyamic files and the files outside it as static files. Hence I have placed Data.xml file directly inside the war.

Now lets have a look at the Data.xml file

Data.xml

<?xml version="1.0" encoding="utf-8"?>
<data>
	<countries>
		<country name="India">
			<capital>New Delhi</capital>
		</country>
		<country name="Japan">
			<capital>Tokyo</capital>
		</country>
	</countries>
</data>

Its a pretty simple xml file that doesnt follow any xml schema (and hence you need to be extra careful about the placement of your tags). Each country has a name and a capital. The name is in the form of attribute of the country tag and the capital is in the form of a nested tag of country. Finally the countries are grouped in a countries tag.

Next shown below is the web.xml file.

web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
	<servlet>
		<servlet-name>XMLDemoServlet</servlet-name>
		<servlet-class>com.shank.xml.demo.servlets.XMLDemoServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>XMLDemoServlet</servlet-name>
		<url-pattern>/xmlDemo</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

The listing below shows our jdo data class for country. Please note the I have omitted the getters and setters so as to keep the unnecessary code to a minimum.

COUNTRY class..

package com.shank.xml.demo.jdo;

import java.util.logging.Logger;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

/**
 *
 * @author shank
 *
 */
@PersistenceCapable
public class Country {

 // the logger for this class
 private static final Logger logger = Logger.getLogger(Country.class
   .getName());

 // the id
 @PrimaryKey
 @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
 private Long id;

 // the name of the country
 @Persistent
 private String name;

 // the name of the capital of this country
 @Persistent
 private String capitalName;

 // constructors
 public Country(String countryName) {
  this.name = countryName;
 }

 // getters and setters...
}

Next in line, the listing below is for the PMF class that applies the singleton pattern to the PersistenceManager instance. This is advantageous as the creation of a persistence manager instance is a very heavy task.

PMF class

package com.shank.xml.demo.jdo;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;

/**
 * @author shank
 * 
 */
public final class PMF {

	private static final PersistenceManagerFactory pmfInstance = JDOHelper
			.getPersistenceManagerFactory("transactions-optional");

	private PMF() {
	}

	public static PersistenceManagerFactory get() {
		return pmfInstance;
	}

}

Next let us have a look at the DatastoreUtilities class. This class has a method for getting a jdo object of a specific class according to its name. Below is the listing for this class

DATASTOREUTILITIES class…

package com.shank.xml.demo.jdo;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;

/**
 * This is the common datastore utilities class.
 * 
 * The functions in this class are static and are the common functions that are required
 * for operating on the datastore
 * 
 * @author shank
 *
 */
public class DatastoreUtilities {
	
	private static Logger logger = Logger.getLogger("CommonDatastoreUtilities");
	
	/**
	 * This is the generic Helper method to check if an entity of a particular name exists in the 
	 * particular class entities. It also needs a persistence manager instance to execute the 
	 * calls to the database
	 * 
	 * @param <T> 
	 * @param string
	 * @param class1
	 * @param T 
	 * @return
	 */
	public static <T> boolean checkIfEntityExists(String nameToBeChecked,
			Class<T> entityClass) {
		// TODO Auto-generated method stub
		logger.info("inside checkIfEntityExists() : looking for "+nameToBeChecked+" in "+entityClass.getSimpleName());
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		boolean entityExists = false;
		
		Query query = pm.newQuery(entityClass, "name == nameParam");
		query.declareParameters("String nameParam");
		
		List<T> existingEntities = (List<T>)query.execute(nameToBeChecked);
		logger.info("Existing Entities with the same name are : "+existingEntities.toString());
				
		if(existingEntities.size() == 1){
			entityExists = true;
		}
		
		pm.close();
		
		return entityExists;
	}
		
}

We shall now look at the servlet that we shall be using to read the data from our Data.xml file. This shall be done by the custom xml parser that we shall see in the Part-2 of this post. The custom parser shall then create Country objects from this data and persist these Country objects to the Country datastore.

XMLDemoServlet class

package com.shank.xml.demo.servlets;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.*;

import com.shank.xml.CustomXMLParser;

public class XMLDemoServlet extends HttpServlet {
	
	//the logger for this class
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		logger.info("inside doGet()");
				
		logger.info("calling customParser.doParsing()");
		
		//call the doParsing method on our CustomXMLParser
		new CustomXMLParser().doParsing();
		
		resp.setContentType("text/plain");
		resp.getWriter().println("Parsing Done !  Check the datastore");
	}
}

Next shown below is the index.html page that is the default welcome page for the application. It consists of a link with title “xml deml”. When this link is clicked, the control goes to the XMLDemoServlet as defined by the web.xml file.

index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- The HTML 4.01 Transitional DOCTYPE declaration-->
<!-- above set at the top of the file will set     -->
<!-- the browser's rendering engine into           -->
<!-- "Quirks Mode". Replacing this declaration     -->
<!-- with a "Standards Mode" doctype is supported, -->
<!-- but may lead to some differences in layout.   -->

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Hello App Engine</title>
  </head>

  <body>
    <h1>Hello App Engine!</h1>
	
    <table>
      <tr>
        <td colspan="2" style="font-weight:bold;">Available Servlets:</td>        
      </tr>
      <tr>
        <td><a href="xmlDemo">Parse Data.xml</a></td>
      </tr>
    </table>
  </body>
</html>

That is all for part-1 of this post. In part-2 we shall have a look at the CustomXMLParser code that shall do the actual parsing work.

Just switched to Ubuntu from Windows…

June 15, 2011 3 comments

“This was actually my first post… I wrote it the second day after shifting to Ubuntu… The simplicity and total control was amazing.. i was in total awe of the OS… but somehow this post got lost in all the drafts that I have… Just found it yesterday… So here it is ‘My first blog post‘ “

So this would be my first post on this amazing blog of mine.. and what better occasion than my switching over to Ubuntu as my primary desktop OS

For those of you who don’t know what Ubuntu is, its an operating system derived from Debian which in turn is an operating system based on GNU/Linux.. so yeah I have switched to Linux !!

As for the reason for switching from Windows, I was bored with the same interface for the last 7 years (thats when i started using pc)… and of-course there was the issue of my sound driver getting corrupt too often.. while browsing through the Internet, i read somewhere that Linux would lend me safe haven from all these driver corruption and instability issues.. and when i finally did switch, I was not at all disappointed.

The installation was a breeze.. After finishing the installation, it took me just 10 seconds as the booting time !! yes you read it right, 10 seconds !! 10 seconds and the desktop appeared.. and there was no dangling hourglass.. the system was ready to use.. I said to myself, thats not possible and restarted my machine.. this time I was ready, as soon as the desktop appeared i clicked on the firefox icon and to my surprise it opened instantly!! I was impressed.. No more wait at the boot screen and then at the desktop for that hourglass to disappear..

I browsed through the menus just to have a peek at what comes in the 700MB Ubuntu Operating System… yeah just 700MB.. I was thoroughly satisfied with the content that they managed to squeeze in the 700MB install..

The desktop was elegant and clean(by default Ubuntu comes with GNOME, more on GNOME in a later post, for the moment just know that it is a desktop environment).. I liked the default theme too..

I highly recommend you to give it a try.. UBUNTU

Throughout this blog i shall keep posting about my various experiences with Ubuntu and Linux, whatever issues i face and what solutions i found for them.. about the nature of Linux and Ubuntu and why Ubuntu has now become and shall be my primary OS for a long time to come..

I invite you to this journey through the world of Ubuntu Linux and open-source with me… see ya at the next post..

Categories: Ubuntu / Linux

How to open the Google App Engine local datastore viewer

May 28, 2011 2 comments

Google App Engine (GAE) is google’s service that lets you build applications and deploy on their infrastructure.. It provides a SDK and an Eclipse plugin in order to help speedy development of these applications. You can first test your application on your local machine and then deploy to the app engine.

But that all is not related to the issue of this post..

I didnt know how to view the local datastore contents for my GAE application… So when I found it out after a bit searching, I decided to log it here.

To access the local datastore viewer, run the application and in the browser type

http://localhost/_ah/admin

As usual share this info if it helped you..