Best android questions in May 2012

Benefits in Android to importing a library internally vs externally

20 votes

Post ADT 17, non-Android libraries need to be included either in the "libs" folders of the project or exported via the "Order and Export" tab in the build path. What's the difference (if any) between importing a library externally:

External1

External2

And internally:

Internal2

Internal1

Is there an advantage to importing a library in a way that it is included in the "Android Dependencies" group?

How do you add external jar dependencies into your Android project's build path (internally or externally) make no difference on the actual build process (more specifically at compile and dex step), all it does is to tell build process where to looking for the required jars at compile and dex step.

The Android Dependencies element shown in Java Build Path - Libraries window is just another abstract layer that ADT plugin used for managing/grouping jar dependencies. where your external jar files (in your case android-support-v4.jar) appears (inside or outside Android Dependencies) in that window makes no difference.

Since r17, dependencies management has been much improved, and it is recommended to use libs/ directory store all jar dependencies (refer to you internal way), which is considered as a automation approach (as ADT plugin becomes more smarter now), see Revisions for ADT 17.0.0:

New build features

  • Added feature to automatically setup JAR dependencies. Any .jar files in the /libs folder are added to the build configuration (similar to how the Ant build system works). Also, .jar files needed by library projects are also automatically added to projects that depend on those library projects. (more info)

However, you can still use the old way (refer to you external way) if you prefer, which is considered as a manual approach (as ADT plugin was stupid before), see Recent Changes‎ for r17 Release:

Important: If you are still referencing jar libraries manually instead of putting them under libs/ be aware of the following:

  • If the project is a Library project, these jar libraries will not be automatically visible to application projects. You should really move these to libs/

  • If the project is an application, this can work but you must make sure to mark the jar files as exported.

Is there an advantage to importing a library in a way that it is included in the "Android Dependencies" group?

Automation vs. Manual from dependency management perspective, automation is always considered as more errorless than manual in the world of computer science.

How to maintain a paid and free version of an app

15 votes

I have built a free version of a game app which is now on the market with a name like com.mycompany.myfreegame. Now I want to make a paid version. There will no doubt be tweaks and bug-fixes to both versions required for years to come so I want to encapsulate the encoding of the free vs paid information in as compact a way possible so that I can essentially fix bugs in both versions simultaneously.

If the entirety of the differences between the two versions was handled at runtime then I could set a single flag in the source code and that would be the end of the problem. Unfortunately there are two other things to consider,

  1. The name of the package needs to be different between the two versions.
  2. Some xml needs to be different. For example the free version needs linear Layouts for holding ads, the paid version does not.

What is the simplest way to achieve this goal?

I think the first approach I'd try is using 3 projects in Eclipse: one for either version of the game, and a library project with all of the shared code. The library project would be where all the code for your core gameplay goes, and the version specific projects manage loading different layouts, putting ads in the free version, and adding levels/features/hats to the paid version.

You might be able to accomplish your goal of a single code base with a compiler flag using an ant task, but that's beyond me.

Benefits of compiling C code with gcc's C++ front-end

13 votes

I am very interrogative and perplexed by this commit on android's dalvik platform pushed a year ago.

File extensions were changed to C++ extensions in order to "move the interpreter into C++" - use the compiler's C++ front-end.

What could be the benefits of this change ? Dalvik Platform is a 100% C & asm project and not any C++ feature is used.

I can only speculate, but considering how the Android system has grown in complexity, the scoping features of C++ (classes and namespaces) might make the code base more manageable.

EDIT

Even if the project doesn't currently make use of any C++ features, they may simply be planning ahead.

Apart from some minor differences (namely some parameter conventions most people avoid anyway), C source code compiles as C++ without modification. That being said, in some areas C++ syntax is stricter than C (C allows you to assign a void pointer to another pointer type without a cast; in C++, this is an error), and enforcing this strictness avoids problems down the road. *

*) (That's an overly simplistic view, see comment)

One further reason for the change may be that because most modern development favors C++ over C, a richer set of tools is available.

Speculating again, but at the birth of Android C may have been the only viable option for embedded device development, and now that restriction is no longer an issue.

Touchscreen gestures list and names

12 votes

Where can I find a list of all (many) touchscreen gestures including complex 4 and 5 finger ones for iPad, with a reasonable technical implementation guidelines and code (C++/Java) examples?

After two days of search i have found these links:

http://en.wikipedia.org/wiki/Multi-touch#Multi-touch_gestures - simple gestures

http://blogs.computerworld.com/18672/the_lion_multitouch_gesture_guide - more complex multi-finger gestures on Apple devices

http://medialoot.com/item/40-vector-multitouch-gestures - 40 multitouch gestures

Unfortunately, nothing usable was found in the Apple's patents regarding gestures.

Android : 4.0.3 emulator closed automatically after some time

11 votes

I am working on emulator 4.0.3, whenever runs the project new android emulator gets started , and previous emulator show blank screens i.e become idle with blank scrren doesn't work anything. can anyone please say me , what will be the problem.How shall i solve it.... can anyone answer it..

got error while reseting adb

[2012-05-11 16:54:11 - DeviceMonitor] Adb connection Error:An existing connection was forcibly closed by the remote host
[2012-05-11 16:54:11 - Unexpected error while launching logcat. Try reselecting the device.] An existing connection was forcibly closed by the remote host
java.io.IOException: An existing connection was forcibly closed by the remote host
at sun.nio.ch.SocketDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(Unknown Source)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
at sun.nio.ch.IOUtil.read(Unknown Source)
at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:395)
at com.android.ddmlib.Device.executeShellCommand(Device.java:397)
at com.android.ddmuilib.logcat.LogCatReceiver$1.run(LogCatReceiver.java:102)
at java.lang.Thread.run(Unknown Source)

[2012-05-11 16:54:12 - DeviceMonitor] Connection attempts: 1

The emulator image shown below..

Valid XHTML.

and it is very slow.. when i tried to increase device ram size from 512 to 1024 in emulator it doesn't worked for me.. please anybody help me out. Thanks..

I was having same problem.. I have just recreated i.e re-installed eclipse & android sdk.. it works fine for me.. hope it ll help for you too..

How can I examine the whole source tree with an annotation processor?

10 votes

I have a lot of handler classes that handle specific message types. To register all these handlers, I need to know which ones exist. Currently, they're all annotated with a specific annotation, and I use a Java 6 annotation processor to get all of them, and make a Register class that holds an instance of each of the annotated types.

This works great if the whole tree is being built at once, but if just one of the annotated classes is being built (when I save the file in Eclipse, for example), the processor only sees that type, and builds an incomplete Register. How can I examine the other types in this scenario?

I've solved this well enough for now. What I did is a little hackey, but basically for every annotated class I see, I add its name to a HashSet. Then I use Filer.getResource() to get open a file where I've recorded all the previously-seen annotated classes, and add those to the HashSet too. Then I generate the register class, and write the whole HashSet out to the same resource with Filer.createResource(). This will cause problems if I delete an annotated type, since it will still be recorded in that file, but I can just clean the project or delete that file to solve it.

EDIT: Also, I believe that passing the appropriate "originating elements" to Filer.createSource() should allow Eclipse to track those dependencies properly, but it doesn't. Perhaps that's an Eclipse bug.

How to implement Flipboard ipad page turning animation for view flipper in android?

9 votes

Trying to implement page turning animation exactly as the flipboard ipad app. I have referred some blogs and following links :

Android: How to make the flip animation for android activity, as like iphone flip horizontal from left to right?

How to do page flip/turn/curl effect in android

but able to implement only the normal page curl effect. Is there a way to implement the page turning effect for view flipper similar to flipboard ipad app in android? The flipboard ipad app animation is as in the following link :

Flipboard ipad app

Here is a good tutorial that explain this principle(it's implemented with Flex, but works with android too).

How to preserve XML nodes that are not bound to an object when using SAX for parsing

5 votes

I am working on an android app which interfaces with a bluetooth camera. For each clip stored on the camera we store some fields about the clip (some of which the user can change) in an XML file.

Currently this app is the only app writing this xml data to the device but in the future it is possible a desktop app or an iphone app may write data here too. I don't want to make an assumption that another app couldn't have additional fields as well (especially if they had a newer version of the app which added new fields this version didn't support yet).

So what I want to prevent is a situation where we add new fields to this XML file in another application, and then the user goes to use the android app and its wipes out those other fields because it doesn't know about them.

So lets take hypothetical example:

<data>
  <title>My Title</title>
  <date>12/24/2012</date>
  <category>Blah</category>
</data>

When read from the device this would get translated to a Clip object that looks like this (simplified for brevity)

public class Clip {
  public String title, category;
  public Date date;
}

So I'm using SAX to parse the data and store it to a Clip. I simply store the characters in StringBuilder and write them out when I reach the end element for title,category and date.

I realized though that when I write this data back to the device, if there were any other tags in the original document they would not get written because I only write out the fields I know about.

This makes me think that maybe SAX is the wrong option and perhaps I should use DOM or something else where I could more easily write out any other elements that existed originally.

Alternatively I was thinking maybe my Clip class contains an ArrayList of some generic XML type (maybe DOM), and in startTag I check if the element is not one of the predefined tags, and if so, until I reach the end of that tag I store the whole structure (but in what?).. Then upon writing back out I would just go through all of the additional tags and write them out to the xml file (along with the fields I know about of course)

Is this a common problem with a good known solution?

-- Update 5/22/12 --

I didn't mention that in the actual xml the root node (Actually called annotation), we use a version number which has been set to 1. What I'm going to do for the short term is require that the version number my app supports is >= what the version number is of the xml data. If the xml is a greater number I will attempt to parse for reading back but will deny any saves to the model. I'm still interested in any kind of working example though on how to do this.

BTW I thought of another solution that should be pretty easy. I figure I can use XPATH to find nodes that I know about and replace the content for those nodes when the data is updated. However I ran some benchmarks and the overhead is absurd in parsing the xml when it is parsed into memory. Just the parsing operation without even doing any lookups resulted in performance being 20 times worse than SAX.. Using xpath was between 30-50 times slower in general for parsing, which was really bad considering I parse these in a list view. So my idea is to keep the SAX to parse the nodes to clips, but store the entirety of the XML in an variable of the Clip class (remember, this xml is short, less than 2kb). Then when I go to write the data back out I could use XPATH to replace out the nodes that I know about in the original XML.

Still interested in any other solutions though. I probably won't accept a solution though unless it includes some code examples.

Here's how you can go about it with SAX filters:

  1. When you read your document with SAX you record all the events. You record them and bubble them up further to the next level of SAX reader. You basically stack together two layers of SAX readers (with XMLFilter) - one will record and relay, and the other one is your current SAX handler that creates objects.
  2. When you're ready to write your modifications back to disk you fire up the recorded SAX events layered with your writer that would overwrite those values/nodes you have altered.

I spent some time with the idea and it worked. It basically came down to proper chaining of XMLFilters. Here's how the unit test looks like, your code would do something similar:

final SAXParserFactory factory = SAXParserFactory.newInstance();
final SAXParser parser = factory.newSAXParser();

final RecorderProxy recorder = new RecorderProxy(parser.getXMLReader());
final ClipHolder clipHolder = new ClipHolder(recorder);

clipHolder.parse(new InputSource(new StringReader(srcXml)));

assertTrue(recorder.hasRecordingToReplay());

final Clip clip = clipHolder.getClip();
assertNotNull(clip);
assertEquals(clip.title, "My Title");
assertEquals(clip.category, "Blah!");
assertEquals(clip.date, Clip.DATE_FORMAT.parse("12/24/2012"));

clip.title = "My Title Updated";
clip.category = "Something else";

final ClipSerializer serializer = new ClipSerializer(recorder);
serializer.setClip(clip);

final TransformerFactory xsltFactory = TransformerFactory.newInstance();
final Transformer t = xsltFactory.newTransformer();
final StringWriter outXmlBuffer = new StringWriter();

t.transform(new SAXSource(serializer, 
            new InputSource()), new StreamResult(outXmlBuffer));

assertEquals(targetXml, outXmlBuffer.getBuffer().toString());

The important lines are:

  • your SAX events recorder is wrapped around the SAX parser
  • your Clip parser (ClipHolder) is wrapped around the recorder
  • when the XML is parsed, recorder will record everything and your ClipHolder will only look at what it knows about
  • you then do whatever you need to do with the clip object
  • the serializer is then wrapped around the recorder (basically re-mapping it onto itself)
  • you then work with the serializer and it will take care of feeding the recorded events (delegating to the parent and registering self as a ContentHandler) overlayed with what it has to say about the clip object.

Please find the DVR code and the Clip test over at github. I hope it helps.

p.s. it's not a generic solution and the whole record->replay+overlay concept is very rudimentary in the provided implementation. An illustration basically. If your XML is more complex and gets "hairy" (e.g. same element names on different levels, etc.) then the logic will need to be augmented. The concept will remain the same though.