Idea intellij “USB device not found” Android problem

Lately I’ve been really frustrated with this message. I don’t know when it has started to pop up, but every time I’m in the middle of important debugging, and want to restart the app I get this message when starting the app:

USB device not found

I’ve read bunch of blogs and stackoverflow questions and answers but nothing helped. Then I tried one very simple trick:

adb kill-server
adb devices

After that I’ve got this response:

* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
37329B0B96FD00EC    device

After that intellij worked without problems.

Advertisements

iOS Fragmentation – iCloud style

To be clear from the start, I’m talking from development’s point of view, not percentage of devices getting new OS versions. Just good old code :)

Since iOS version 5.x there is a fragmentation in iOS that I really don’t like. Since my app was rejected from the appstore I started reading more about iCloud and how it has been implemented in different iOS versions.

Official reason why my app was rejected is:

We found that your app does not follow the iOS Data Storage Guidelines, which is required per the App Store Review Guidelines.

That sounded OK, I’m not complaining, I was unaware of iCloud integration to be honest (or how deep the integration is). In the same message from apple, I’ve got a hint to take a look at this Q&A.

To make a long story short:

  1. iOS 4.x: There is no iCloud sync, so you can store your files in /Documents folder without any problems.
  2. iOS 5.0: Everything in /Documents folder is synced with iCloud, so you have to put your files in /Cache. The only problem is that when your iDevice runs out of space, your cache folder will be deleted most likely.
  3. iOS 5.0.1: You can set a “don’t sync” this file/folder inside your /Documents folder. That is pretty good, but this code is only for this version
    #import <sys/xattr.h>
    - (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
    
      assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
    
      const char* filePath = [[URL path] fileSystemRepresentation];
      const char* attrName = "com.apple.MobileBackup";
    
      u_int8_t attrValue = 1;
    
      int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    
      return result == 0;
    
    }

    Apple marked this code as deprecated for later version of iOS

  4. iOS 5.1+ (currently 5.1 and 5.1.1): You can also flag files or folders, so that they are not synced to iCloud. Here is the snippet:
    - (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
      assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
    
      NSError *error = nil;
      BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                    forKey: NSURLIsExcludedFromBackupKey error: &error];
    
      if(!success){
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
      }
    
      return success;
    
    }

Also in my app I’ve added a small piece of code that handles iOS updates. For example if user had my app with 5.0 and then updates to 5.0.1 or similar.
After applying these snippets to my app it was approved without problems.

So the only thing I’m wondering is why isn’t iCloud handling as elegant as most of iOS features? :)
It’s not that bad, but I don’t like it.

Passing objects from one Activity to another

When you want to transfer some parameters (String, int, whatever) in Android you can pass it via one of the Intent.putExtra methods. It’s simple as that. You can say:

int parameter = 42; // just an example

Intent intent = new Intent(currentActivity, newActivity.class);
intent.putExtra("myParameter", parameter);
startActivity(intent);

But what happens when you want a pass your custom made class instance? You can pass:

  1. it’s id and gather it from db or web service for example. That’s OK, but it’s a bummer if you have already have it, why do the same thing again?
  2. your class could implement Serializable interface. This is a perfectly working solution, but as many people said, it’s not an optimal solution (just take a look at stackoverflow)
  3. or use android’s Parcelable interface :)

Just to be clear, I don’t like implementing additional serializing/deserializing code, but as it turns out, it’s pretty simple to implement it, and it improves performance. So why not? :)

To make your class Parcelable, you have to implement the following methods:

int describeContents();
void writeToParcel(Parcel dest, int flags);

And you have to define a public static field named CREATOR (that implements Parcelable.Creator<T>)

Just take a look this example:

import android.os.Parcel;
import android.os.Parcelable;

import java.util.Date;

public class ExampleParcelable implements Parcelable {

   private String stringValue;
   private Integer integerValue;
   private char charValue;
   private boolean boolValue;
   private Date dateValue;

   @Override
   public int describeContents() {
      return 0;
   }

   @Override
   public void writeToParcel(Parcel dest, int flags) {
      dest.writeString(stringValue);
      dest.writeInt(integerValue);
      dest.writeInt(charValue); // yup, it's actually a char
      dest.writeInt(boolValue ? 1 : 0); // can't store bools, but we can do it this way
      dest.writeLong(dateValue.getTime()); // same here, can't write date's, but we can get time in long
    }

    // Added this default constructor in case you are using some JSON/XML whatever parsers that require no-arg constructor
    public ExampleParcelable() { }

    /**
    Just to make life easier, I've added a constructor that creates our ExampleParcelable from a Parcel (of course, you don't have to do it that way)
    */
   public ExampleParcelable(Parcel parcel) {
       // The only important thing is to read them in the same
       // order as you wrote them (take a look at writeToParcel)
       stringValue = parcel.readString();
       integerValue = parcel.readInt();
       charValue = (char) parcel.readInt();
       dateValue = new Date(parcel.readLong());
   }

   public static final Parcelable.Creator CREATOR = new Creator<UserContentInfo>() {

    @Override
    public ExampleParcelable createFromParcel(Parcel source) {
       return new ExampleParcelable(source);
    }

   @Override
   public ExampleParcelable[] newArray(int size) {
      return new ExampleParcelable[0];
   }
};

}

It’s pretty much straight forward. In writeToParcel method you need to write fields that you need (in case you don’t want to pass every field), and later in CREATOR’s createFromParcel read every field in the same order you’ve written to Parcel in the first place.

I’ve added an example how can you write, and later read char and date types. Because can’t write everything (but it can write other Parcelables in case you need it).

Using it is the same thing as in the first example

ExampleParcelable test = new ExampleParcelable(); // just an example, set fields you need

Intent intent = new Intent(currentActivity, newActivity.class);
intent.putExtra("myParameter", test);
startActivity(intent);

Also, in case you are super-lazy to implement your own Parcelables, I’ve found this awesome project (source code: https://github.com/dallasgutauckis/parcelabler).
It creates them for you :)

Mavenizing android projects

I must confess, I like building my java apps with maven because I really hate managing all the dependencies, and on the other side I can use great tools like sonar and jenkins/hudson out of the box.

So the goal was to build my android project with maven.  First stop was of course the official android-maven url: http://code.google.com/p/maven-android-plugin/

In the getting started it was pretty clear to install jdk, android sdk, maven and that’s about it. I’ve created my pom file like they said:

<dependency>
   <groupId>com.google.android</groupId>
   <artifactId>android</artifactId>
   <version>1.6_r2</version>
   <scope>provided</scope>
</dependency>

In the project I’m talking about, I’m using android 1.6. After mvn clean install I had my first problem.

1. Maps not found

package com.google.android.maps does not exist

So that was pretty clear that I only have “clean” android installed (or at least in my mvn repo). After a quick google search, I’ve found out about mvn android sdk deployer (https://github.com/mosabua/maven-android-sdk-deployer). That seemed to be the answer to my problems. Yup, just clone the repo, mvn clean install it and you’re ready to go. But after running mvn clean install (for maven android sdk deployer) I’ve got the following error:

2. addon-google_apis-google-3/source.properties not found

Failed to execute goal org.codehaus.mojo:properties-maven-plugin:1.0-alpha-2:read-project-properties (default) on project google-apis-3: Properties file not found: /Users/vuknikolic/dev/android-sdk-mac_x86/add-ons/addon-google_apis-google-3/source.properties -> 

This one confused me, I knew that I had google add-on installed for v3, I’ve checked the path, but it wasn’t there. Then I saw on maven-android-sdk-deployer’s github page:

Platforms and Add on folder names changes in SDK

When updating an existing android sdk install the add-ons subfolder can sometimes be reused and their contents be updates so you could end up with e.g. the google maps-4r2 in a folder named google_apis-4_r01. To work around this just uninstall the affected add-on and reinstall it with the android sdk tool.

After that android mvn deployer worked like a charm, great works guys. So I’ve returned to my project, started mvn clean install… and…

3. JSON not found?

package org.json does not exist

This one seemed weird, cause why on earth would I miss something inside of android sdk? If it is installed already… My good friend Google saved me again (http://code.google.com/p/maven-android-plugin/issues/detail?id=77), there seems to be a problem with 1.6_r2 package as well, so I had to upgrade it to 2.1.2 as advised in that issue.

After that I was finally building my android project with maven. So here are the five easy steps to start building your android project (that uses google maps) with maven:

  1. Create pom.xml and set version to 2.1.2 or above in maven dependency
  2. Clone maven-android-sdk-deployer
  3. Uninstall old installed versions with Android SDK manager and install them again (just to make your life easier)
  4. Start mvn clean install in maven-android-sdk-deployer
  5. Start mvn clean install in your project

Super easy iOS XML parsing

I just love it when you need something simple and easy that perfectly suits your needs. I needed some lightweight XML parser for iOS, and I found it.

To be honest (since I’m coming from java background), I didn’t quite fall in love with objective-c at first, and it seemed to be that I needed a lot more code to make some basic stuff work. For example XML parsing. NSXMLParser is ok, but it’s event driven (link #1, link #2). I wanted some dead simple DOM parser.

So the whole library is just two classes SMXMLElement and SMXMLDocument. To show you how simple it is to parse a file, here is a (reduced) snippet from my application:


- (void) parseData:(NSData *) {

   NSError *error;
   SMXMLDocument *document = [SMXMLDocument documentWithData:data error:&error];

   // check for errors
   if (error) {
   DDLogError(@"Error while parsing the document: %@", error);
   return nil;
}

// Array of objects that we are returning
NSMutableArray *result = [[NSMutableArray alloc] init];

// Get the videos node
SMXMLElement *videos = document.root;

// Go through every sub-element "video"
for (SMXMLElement *video in [videos childrenNamed:@"video"]) {
   VideoInfo *info = [[VideoInfo alloc] init];
   info.name = ;

   // Get other values from XML...
   [result addObject:info];
   [info release];
}

return result;
}

A shorter version of XML that the code above parses is:


<videos>
   <video>
      <name>Yup, this a name of a video</name>
   </video>
   <video>
      <name>And another one :)</name>
   </video>
</videos>

As you can see I’m only using (NSString*) valueWithPath:(NSString *) here, but there are a couple more


- (SMXMLElement *)childNamed:(NSString *)name;
- (NSArray *)childrenNamed:(NSString *)name;
- (SMXMLElement *)childWithAttribute:(NSString *)attributeName  value:(NSString *)attributeValue;
- (NSString *)attributeNamed:(NSString *)name;
- (SMXMLElement *)descendantWithPath:(NSString *)path;
- (NSString *)valueWithPath:(NSString *)path;

Do you really need anything else (in some small applications)? :)
Really awesome, kudos to the creators.

Twitter bootstrap and Google maps v3

I was playing around with excellent twitter bootstrap and google maps javascript api (version 3), and for some time I had problem with displaying infowindows (“map bubbles”).

Everything went smooth, markers were animated (and in right position), click events were working, except that info windows were looking pretty strange.

As you can see something went wrong with css, I saw that somehow google’s image http://maps.gstatic.com/mapfiles/iw3.png is not showing as it should.
After some hacking I found out that bootstrap defined this (with some other properties):

img {
    max-width: 100%;
}

but gmaps isn’t handling that as it should.

So the answer is to override that property for your google map div (#gmap is div’s name in my project)


#gmap img {
    max-width: none;
}

And here is the result (the bubble is ok, with text, close button, pointer… everything :))

It looks pretty simple, but it took me some time to find it out, because my first suspect was my own code. In the end I was surprised that it wasn’t up to me :)

I hope this will help somebody :)

Android presentation, prezi and general impression

This is my first post without any code, but I just had to express myself :)

Today I had my first non-JavaSvet presentation (for those who don’t know JavaSvet is the first serbian Java user group). It was organized by the great people in SEE ICT organization. I wasn’t the only speaker,  a friend of mine Vladan Petrović  was in it as well, and he made this awesome presentation in prezi (I’ve helped with the content, not that much with the overall design). You can find the presentation here.

Photo by Vladimir Trkulja

I must say that I am pretty impressed how fast it was to make a presentation, and how effective it looks like. I saw that some people in the audience were impressed. And also, this was my first time presenting something that is inside a browser, and not powerpoint/open(libre)office. So it was all pretty new for me.

The goal was to first explain android basics, and later give them some small exercises that they can work on. We decided to test them with a little bit of tic-tac-toe. We’ve showed all the basics with this little example that I have made (github link). In case you need it, you can find there some basic examples of activities, services, broadcast receivers and content provider. Basically all-in-one example. It’s a small, but functional mp3 player (actual song isn’t hosted @ github). To make things more geeky, I’ve selected Paranoid Android by Radiohead (OK Computer album), cool eh?

The thing that totally blew me away was that when I got back home, I’ve already had some facebook invites, and tweets, that people continued working on the example as their first project.

I would be the luckiest man if any of those guys keep on working, and if they can make some cash out of it, that would be more than amazing. So thumbs up for everybody :)

UPDATE: Great guys from start it uploaded the video to youtube.

JavaMail, Spring and Google apps mail

Whoa, second post in one day :)

In my application I want to use spring’s mail sender with my google apps account. I was getting:

org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first

After a little bit of help form my dear friend, I found out that all you need to do is:

<bean id="javaMailSender">
   <property name="host" value="${mailer.host}"/>
   <property name="username" value="${mailer.user}"/>
   <property name="password" value="${mailer.pass}"/>

   <property name="defaultEncoding" value="${mailer.encoding}"/>

   <property name="javaMailProperties">
      <props>
         <prop key="mail.smtp.auth">true</prop>
         <prop key="mail.smtp.starttls.enable">true</prop>
      </props>
   </property>
</bean>

Take a look at the javaMailProperties element. Yup. That’s all you need to add to your configuration xml.

Spring Security, OpenId and special characters

I wanted to enable open id login with spring security 3.0.7. I’ve used google as a open id provider.
Setup was pretty easy, everything by the book. I’ve tried with couple of accounts and everything was ok.

But when I tried to use my “official” google account, I’ve ran into a problem. My account couldn’t pass the verification. In log files I’ve found this:

Verification failed for: [http://somedomain] reason: null

Reason null. Whoa, too much information :)

Googling didn’t help much, until I’ve realized that the problem was in encoding. Yup, all accounts worked except mine… and I have the letter ć in my surname. I guess the same problem would be with umlauts and similar.

The easiest fix was to add just one attribute to the Connector element in server.xml tomcat configuration. The magical attribute is:

URIEncoding="UTF-8"

Hibernate Audit logging – the easy way!

Let’s say you are working on an application where users are constantly adding/changing  new content. You will most likely have to keep a record what’s going on. For example you want to make a wiki-like software, it is crucial to keep a log who added/updated/deleted wiki entries.

If you need that functionality, and you are using Hibernate, then you are one happy coder! Enter ENVERS! As the good people at jboss site say: Easy Entity Auditing.

Here is what you need to do make your entities auditable:

  1. Download latest hibernate with envers bundled (I’m using 3.6.0.Final) and add it to your classpath
  2. Add envers event listeners to your session factory (I’m using spring in my project, so here is a part of my spring.xml):
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
       <!-- Envers - Auditlogging -->
       <property name="eventListeners">
          <map>
             <entry key="post-insert"><ref local="enversListener" /></entry>
             <entry key="post-update"><ref local="enversListener" /></entry>
             <entry key="post-delete"><ref local="enversListener" /></entry>
             <entry key="pre-collection-update"><ref local="enversListener" /></entry>
             <entry key="pre-collection-remove"><ref local="enversListener" /></entry>
             <entry key="post-collection-recreate"><ref local="enversListener" /></entry>
          </map>
       </property>
    </bean>
    <bean id="enversListener" class="org.hibernate.envers.event.AuditEventListener" />
    
  3. Annotate your class with @Audited. If you don’t want to keep track of all properties, just annotate the fields you need with the same @Audited.

And that is it :)

After completing all the three steps you will see new table called revinfo (that keeps all the revisions information, you can change it’s name, prefix/suffix, check out the docs) and <entity>_aud (log for the specified entity).

I had a problem that <entity>_aud didn’t have all the required fields, even with hibernate.hbm2ddl.auto set to update. Adam Warski (great guy that create Envers, thanks man!)  gave somebody a great tip in jboss forum, that helped me. I’ve just added @Audited for my getters and everything worked smoothly.

One thing I needed more is to keep track WHO made the changes. Here is a nice tutorial how to do that. To keep it short:

  1. Extend DefaultRevisionEntity and annotate it with @RevisionEntity
    @RevisionEntity(PectopahRevisionListener.class)
    public class PectopahRevisionEntity extends DefaultRevisionEntity {
    	private String username;
    
    	public String getUsername() { return username; }
    	public void setUsername(String username) { this.username = username; }
    }
    
  2. Create your own RevisionListener
    public class PectopahRevisionListener implements RevisionListener {
        @Autowired
        private UserService userService;
        @Override
        public void newRevision(Object revisionEntity) {
               PectopahRevisionEntity pectopahRevisionEntity = (PectopahRevisionEntity) revisionEntity;
               User user =  userDetails.getCurrentUser();
               pectopahRevisionEntity.setUsername(user.getUsername());
            }
        }
    }
    
  3. In case you are using hbm.xml files (like me), add the following:
    <hibernate-mapping package="...your package...">
    	<class name="PectopahRevisionEntity" table="revinfo">
            <id name="id" type="int">
    			<column name="rev" not-null="true"/>
    			<generator class="native"/>
    		</id>
            <property name="timestamp" type="long" column="timestamp" />
    		<property name="username" type="string" not-null="true"/>
    	</class>
    </hibernate-mapping>

    (here you could rename table’s name and/or fields).

Simple as that. There is also a simple mechanism how to retrieve info from audit log, but I’ll maybe cover that some other time, it’s almost 1am :)

It makes me really happy to find great tools like this one. Easy to setup, clean and simple API, and yeah it does the job!