Best android questions in June 2011

13 votes

I'm working on an Android project and I would like to know any recommendations about what's a good architecture to build an android application.

I want to use dependency injection using Roboguice and I've been reading about MVVM pattern or MVC pattern (Android MVVM Design Pattern Examples).

Also I know that roboguice have a pretty cool Context-Based Event's raising and handling feature that could be very testable as the code is decoupled.

Any recommendations on a working design pattern? a testable and scalable architecture you have worked with or developed?

The Android platform provides a common set of design patterns, and with the limited hardware resources you get compared to Web-apps it is still often best to stick with using these directly in production code. There are other frameworks that sort of "wrap" the base platform; these are worth looking into if you have a specific purpose (or perhaps for prototyping/experimenting), but for the best level of support you are generally best sticking with the standard components.

This is a great resource when working on UI solutions: http://www.androidpatterns.com/

Specifically for DI: There is a Spring framework for Android, I've had a play with it and it looks quite promising. You've already mentioned Roboguice as another alternative to this. However, to avoid performance and library overhead, I still find the easiest approach is to write a simple reflection-based class that registers and injects dependencies within my own code. Similar to this approach, except I usually move the injection code into a separate singleton and reference it from there.

In my experience most of the third-party offerings are not yet mature enough to rely on right now, and don't really give you much on top of what the base platform provides. They are constantly progressing, however, so be sure to experiment with the big names from time-to-time.

android:windowBackground="@null" to improve app speed

11 votes

I just read a blogpost by Romain Guy on how to speed up an app UI. He basically says that if your app uses opaque views you can set the background to @null in your Activity's style using:

<item name="android:windowBackground">@null</item>

Does this work? I was willing to test this using FPS as he did but I didn't find a clear way of getting that info.

I have read some threads saying you need to do it yourself. I am about to add a custom view that draws the FPS in the onDraw() method and calls invalidate() to get call all the time.

Although this works, I would like to know if there is a better way to analyse FPS in an application.

That blogpost has a source code of samples. Check FpsImageView.java.

Questions about preparing an apk for the Amazon Android App Store

10 votes

Amazon's documentation is surprising lacking in information about the submitting binary process. From what I can tell, you submit an unsigned binary and they wrap it in their own code and produce a signed apk?

This leaves several questions:

  1. Does the Amazon App Store perform a zipalign for you?
  2. If you have your app in the Android Market (Google's) already, is it recommended to use the same package name or a different one? Does it make any difference?
  3. I also saw elsewhere, that they offer the option to download the apk they prepare and sign it with your own key. Is it recommended to take this and then sign it with the same key you are using in the Android Market? Does it make any difference?

Are there any other considerations or pitfalls that one should know before diving into this process?

Thanks

  1. Yes. Amazon wraps your binary with code specific to their appstore that allows them to collect analytics data and enforce DRM. The app will be repackaged after that.

  2. You should use the same package name. The Amazon distribution agreement currently has a number of provisos; e.g., that your app is not priced lower on another app store. They also do occasional checks to see whether the version of your app on the market is up to date. These checks are primarily done using the package name; changing the package name of your app could easily be viewed by them as a means to evade the terms of the agreement.

  3. No. There may be good reasons why one would want to do this, but none that I can think of. By default, Amazon signs your apk with a signature that is specific to your Amazon developer account.

Other:

Read this. In particular, ensure that the app links correctly to the Amazon app store and not the Android market, or others. I don't have inside data, but I'd wager a fair amount that the vast majority of submissions that Amazon turn down fall afoul of that requirement.

Doubt in drawing custom view using android

9 votes

I am drawing a custom view in my application which basically takes arguments(XML ) as the text to display and then keeps on rotating it infinitely.

While I was making this control I had a few doubts which I want to ask:

  • I have made 2 of my stylable attributes which I have declared in the attrs.xml file. These attributes are to set the width and the width of the circle used in my control. These values I would use in the ondraw method and the onmeasure method. I ran my program by declaring just these but there was an error which asked me to put android:width and android:height attributes. My question is why would I need those if I am already using my custom attributes to define the height and the width of my view

  • I am coding on a mac. Now when I was making my attrs.xml file, to get the autocomplete list which we usually get by ctrl+space was not showing up. Why is that. For e.g., i wanted to know what values can I give the format attribute of my custom attribute that like I am demostrating in the following: <attr name ="somename" format="value I wanted to find out through autocomplete"> . Why is the autocomplete not popping up? It does pop up when I am making a.java file.

  • In my ondraw() method I wanted to draw a circle. Now for this I would require the co-ordinates of the center of the circle. So what I do is put 0, 0. But this is not correct. I want the circle to be at the center of the parent view it is in. So if my view is in a hierarchy I want it to respect that. I want to give the co-ordinates relative to the parent view. What is happeining right now is that it is being drawn at the top left corner of my screen. This is what I don't want. What do I do to achieve this?

why would I need those if I am already using my custom attributes to define the height and the width of my view?

This is because Android needs to know how and where to put your view in the layout. You can implement your view to make use of your custom height/width requirements by overriding View.onMeasure() to return your own size parameters. You can then just set android:layout_width="wrap_content" android:layout_height="wrap_content" in your layout file.

Why is the autocomplete not popping up? It does pop up when I am making a.java file.

Autocomplete and autodoc implementation for Android xml files is shaky at best, so it's not really surprising that it doesn't work. I'm not aware of a fix and AFAIK it's an IDE bug.

In my ondraw() method I wanted to draw a circle. Now for this I would require the co-ordinates of the center of the circle. So what I do is put 0, 0. But this is not correct. I want the circle to be at the center of the parent view it is in. So if my view is in a hierarchy I want it to respect that. I want to give the co-ordinates relative to the parent view. What is happeining right now is that it is being drawn at the top left corner of my screen. This is what I don't want. What do I do to achieve this?

If you implemented onMeasure() correctly, the coordinates relative to parent should be taken care of already. To get the center of your view use the following code:

void onDraw(Canvas canvas)
{
int centerX = this.getWidth() / 2;
int centerY = this.getHeight()) / 2;
//..draw code here
}

Edit
Here's an example with source code that should help: http://mindtherobot.com/blog/272/android-custom-ui-making-a-vintage-thermometer/

Why shouldn't I use the menu icons provided by the OS?

9 votes

I would like to use some of the default menu icons provided by the Android OS.

android menu icons

The XML would be something like this:

<item android:id="@+id/menu_refresh"
   android:icon="@android:drawable/ic_menu_refresh"
   android:title="@string/menu_refresh" />

But the documentation says this is unadvised.

Warning: Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. menu icons under android.R.drawable).

I thought the whole point of using the default icons is because the design does change from OS to OS. By using the default icons, your app will look and feel appropriate for the OS it's running on. So what is so bad about using the default icons? It seems like not using the default icons would hurt the appearance of the app.

The problem is that you are adding in a dependency that google does not guarantee will be static.
The names of these icons could change, the size could change and become incompatible with your app.
If you want icons to be the same as the current google ones, you can use the ones available here

OutOfMemory error while joining large images

8 votes

I am joining two images using the code below but it throws an OutOfMemory error my images are around 1MB each.

private Bitmap overlayMark(String first, String second)
{
    Bitmap bmp1, bmp2;
    bmp1 = BitmapFactory.decodeFile(first);
    bmp2 = BitmapFactory.decodeFile(second);
    if (bmp1 == null || bmp2 == null)
        return bmp1;

    int height = bmp1.getHeight();
    if (height < bmp2.getHeight())
        height = bmp2.getHeight();

    Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth() + bmp2.getWidth(), height,
            Bitmap.Config.ARGB_8888);// Out of memory
    Canvas canvas = new Canvas(bmOverlay);
    canvas.drawBitmap(bmp1, 0, 0, null);
    canvas.drawBitmap(bmp2, bmp1.getWidth(), 0, null);
    bmp1.recycle();
    bmp2.recycle();
    return bmOverlay;
}

Update: I tried below two answers but it still not allwoing me to create bitmap of such big size the problem is that the resultant bitmap is too large in size around 2400x3200 so its going out of memory.

How can I join large images without running out of memory?

Without loading the image into memory, you CAN get the size of the image, using inJustDecodeBounds. The Bitmap returns null, but all the parameters are set. You can scale down the image accordingly.

If your JPEG images are 1 MiB each, conversion to a BMP will take a lot of memory indeed. You can easily calculate its BMP equivalent by the dimensions of the image. Conversion of such a large image is expected to crash indeed. Android limits its apps to 16 MiB VM only.

Also use RGB_565 instead of ARGB_8888.

So your only solution is: (a) To use BitmapFactory.Options.inSampleSize to scale down the image or (b) Use Android NDK where the 16 MiB limit isn't there.

JNI: From C code to Java and JNI

8 votes

Background

I am developing an application for android in eclipse and now I have a problem and I need your help. So I must Call function written in C from JAVA application. But on my way of writing code I have some Questions which you can see below. I am waiting for your answers and ideas ...

C Code:

typdef struct blobData_s {
    unsigned long length;
    unsigned char data[1];
} blobData_t;

unsigned int CheckEnrollmentExist ( unsigned long hdevice, blobData_t* pInputInfo ) {
    // Function code goes here
    ..........................
    return some_value;
}

JAVA Code:

In JAVA code instead of unsigned long I use int so I can write.

class jblobData_c {
    public int langth;
    *Question 1.*
}

public class ApplicationMainClass extends Activity {
    // Some code goes here
    ......................

    public native int JCheckEnrollmentExist( int jhdevive, *Question 2.* );

}

Question 1.

  • What I can use instead of unsigned char in JAVA Code ?
  • What I must write in JAVA code instead of unsigned char data[1]; ?

Question 2.

  • How I can use class jblobData_c instead of blobData_t* pInputInfo in the JAVA Code ?
  • What I must write in JAVA instead of blobData_t* pInputInfo ?

JNI Code:

JNIEXPORT jint JNICALL Java_com_Test_JCheckEnrollmentExist(JNIEnv* env, jobject obj, jint jhdevice, *Question 2.* ) {

    // Call the base function from C code.
    return CheckEnrollmentExist( jhdevice, *Question 3.*);
}

Question 3.

  • What I must write in CheckEnrollmentExist function that is C Code Function instead of blobData_t* pInputInfo in order this function works right and given parameter be the same

Reference

  1. How to pass C structs back and forth to Java code in JNI ?
  2. Passing large C structure through JNI efficiently
  3. Return a Structure Object from C to Java Through JNI
  4. Pass data between Java and C
  5. Passing a pointer from JNI to Java using a long
  6. Passing pointers between C and Java through JNI

For question #1:

You can use a jchar. Primitive chars in java are not signed, it's about the only primitive that isn't. Note that jchar is a UTF-16 char, so you will have to "map" the jchar to a regular char, as you would have to with any character conversion issue. For simple conversions, this can typically be done by casting

char c_char = (char)java_char;

because the core ASCII shares the same numeric values between ASCII and UTF-16. However, this is prone to error should anyone actually attempt to pass a "special" character through the interface. A much better way would be to (in the java side, as it is easier) convert the characters to bytes using the appropriate character set for your platform (to ensure platform compatibility in the C layers). Then you only need to pass a byte[] to the JNI call, and the bytes will correctly correspond to the characters that C likely will expect.

For question #2:

If your CheckEnrollmentExists(...) method is the JNI binding entry point, you cannot change data types safely. That means that all entry inputs must be JNI data type values. While you might be able to select the C data type equivalents (and you might be able to get your compiler to do it anyway) such techniques should be frowned upon. This implicitly means that JNI entry points cannot accept struct data structure not defined in the JNI headers. In other words, you can't pass your own struct to the method.

If the method needs access to a C struct across calls, use another means. I've seen people store the pointer to the allocated data structure in a member integer or long (doing correct casting). You can then rewrite the native code side to retrieve the pointer from the "this" object being passed into the call, and the do a dereference to obtain the required data.

For Question #3:

This is actually the same as question #2. In the "binding wrapper" you put, you would retrieve the pointer's stored value in the java object's int or long field, cast it to the appropriate struct pointer and then pass it to the internal method. As the passing of the pointer is a C to C call, no extra magic is required.

Android two player game to be played in internet

8 votes

I have developed a simple two player chess game in android to be played using Bluetooth. I want to extend it by making it possible to be played through internet. whenever a player makes a move, the move should be transferred to the other player via internet.

How to make this possible?

I have heard of C2DM mechanism.Does that suites the scenario i described and is it reliable?

Thanks:)

Another option is to use some sort of IM as a communication medium for app. For eg. Use Asmack to connect to XMPP Im like GTalk. Prompt user to create an account there, for your game. And use it to send and receive commands via IM. This way you won't need to setup your mediating server.

This works if user knows who he is playing with. To collect the user data and let them search for available players, you still need to setup a server. IRC chat room may be an option to avoid this also.

  • GTalk was just an example. You can use any IM or IRC also.

Rendering SVG with OpenGL (and OpenGL ES)

8 votes

I am currently investigating the possibility of rendering vector graphics from an SVG file using OpenGL and OpenGL ES. I intend to target Windows and Android. My ideal solution would be to have a minimal C library that generates a polygon triangulation from a given SVG file. This would then generate standard OpenGL or OpenGL ES calls, and use a display list or vbo for optimization when redrawing. I would simply draw a display list to draw the vector image after translating and rotating, allowing me to mix this with other OpenGL calls.

So far I see that the suggestions are to firstly use QT or Cairo. - This is not an option given that I wish to manage my own OpenGL context without bloated libraries (in the context of what I am trying to achieve). Nor is this suitable for Android.

Second option is to use libraries that render to a texture. While this might be ok for static vector graphics, it's not an efficient or feasible option for games where scaling and rotations occur frequently.

Thirdly there is the possibility of using OpenVG. There are some opensource implementations of the OpenVG specification (ShivaVG etc), but I am yet to find a library that is capable of generating the appropriate OpenVG calls from a given SVG file at runtime, and I can't see how to optimize this as we might wish to with a display list or vbo.

All three methods suffer limitations. I think the most promising option is using an OpenVG implementation if no other solution exists. So my question is, are there any libraries out there that do what I want, or close to what I want? If not, is there a good reason why not? And would it be better to attempt to do this from the ground up instead?

From http://shivavg.svn.sourceforge.net/viewvc/shivavg/trunk/src/shPipeline.c?revision=14&view=markup :

static void shDrawVertices(SHPath *p, GLenum mode)
{
int start = 0;
int size = 0;

/* We separate vertex arrays by contours to properly
handle the fill modes */
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, sizeof(SHVertex), p->vertices.items);

while (start < p->vertices.size) {
size = p->vertices.items[start].flags;
glDrawArrays(mode, start, size);
start += size;
}

glDisableClientState(GL_VERTEX_ARRAY);
}

So it does use a VBO. So I'd suggest making your own SVG parser / use a pre-made one, and forward the calls to ShivaVG.

You still have the problem that ShivaVG is in C (and not in Java) and creates an opengl context (and not opengles, if I read the code correctly). So even if you compile it using Android's NDK, you'll have to modify the code ( for instance, I've seen a few glVertex3f around, but they don't seem to be much needed... hope for the best). The other option, of course, it to port the code from C to Java. Maybe not as painful as you could imagine.

Good luck !

Android to node.js communication

8 votes

I saw there are a couple of similar threads but i could not find my answer.

I'm making and android app, an i want to use node as server for realtime communication.

I really cannot get this to work.

Probably i'm making many many things wrong but i like to try to understand.

my server is as simple as

    var http = require('http'),  
    io = require('socket.io'),
server = http.createServer(function(req, res){ 
     res.writeHead(200, {'Content-Type': 'text/html'}); 
     res.end(':)'); 
});
server.listen(8080);
var socket = io.listen(server); 
socket.on('connection', function(client){
    client.send("hello");
    console.log("connected!");
});

and this works... i tried his with a web app and i can connect.

But i can't with java..

i tried kryonet but i get an exception like "connected but timeout on registration"

i tried weberknecht i get a "error while creating socket to ws://184.xxxxxx:8080"

i tried TooTallNate, no luck, it just call onClose method.

i tried jWebSocket but i couldn't get it to work...

So i'm here, asking for help, does anyone knows how to get this done? any suggestion?

P.S. for TooTallNate i'm using something like this:

Net net=new Net(new URI("ws://184.xxxxxx:8080"),WebSocketDraft.DRAFT76);

might the problem be here?

UPDATE: i handled this! after a good sleep i had the idea, i was using socket.io, bad idea... know i use Node Websocket Server with weberknecht. The server looks like this:

var ws = require("websocket-server");

var server = ws.createServer();

server.addListener("connection", function(client){
    console.log("new connection");
    client.send("aaaaaa");
    client.addListener("message", function(msg){
    });
});

server.listen(8080);

and the client:

try {
            URI url = new URI("ws://184.106.69.64:8080/");
            WebSocket websocket = new WebSocketConnection(url);
            websocket.setEventHandler(new WebSocketEventHandler() {
                    public void onOpen(){
                            System.out.println("--open");
                    }    
                    public void onMessage(WebSocketMessage message){
                            System.out.println("--received message: " + message.getText());
                    }   
                    public void onClose(){
                            System.out.println("--close");
                    }
            });

            websocket.connect();
            websocket.send("hello world");
        }
        catch (WebSocketException wse) {
                wse.printStackTrace();
        }
        catch (URISyntaxException use) {
                use.printStackTrace();
        }

Thanks for your help!

I'm the author of node-websocket-server (nws), and I'm pretty sure the reason for node-websocket-server working and socket.io not, is due to the implementation of each. NWS will auto negotiate the right draft to use, and it also has a hopefully 90-100% compliance with the drafts of 76 and 75.

As for socket.io, I can't comment too much, but the last I looked, it's websocket implementation was rather poorly implemented.

I'm currently working on a project at the moment called node-websocket-protocol, which will be able to be used by socket.io, faye, etc as to provide them with a really reliable and compliant websocket implementation. This will also replace the current implementation in node-websocket-server in version 2.0.0.

As a side note, if you'd rather not host your own websocket server, you could look at using Pusher.com, who're actually my employers.

[Update] As for whether websockets are the most appropriate technology choice for your application, is a matter of what type of data and interaction your application needs. On a mobile device, it may be best to use something like urbanairship or notifio if you're just sending push notifications.

Regards, Micheil Smith

Should I open() and close() my SQL database constantly or leave it open?

7 votes

I am creating an app that uses an SQL database for storing data. The way the app is designed it will be updated every 3 minutes or so with new data depending on user actions while the app is running.

In the tutorials I have seen, they recommend that you close the database after changing it (it is an "expensive" in terms of resources).

Is it better to leave it open for the duration of my App since it is being updated on a fairly frequent basis or should I run the close() method immediately after every change?

I guess my worry is that opening it and closing it constantly will draw more resources than it would to leave it open the entire time.

I tried to leave a connection open once -- I used it to stuff a repeater or something -- can't remember now.

Later in the program, I had another need to use the connection -- I think I had it so that when a user clicked a parent item in the repeater, a detail div would pop-up with more information for that item. This generated an error -- something to the effect of 'cannot open() on an open connection'.

I think the error might have been avoidable another way (like checking to see if the connection I was trying to open was already open), but as I thought about it, I realized I'd have to make that a standard practice throughout my app, and that seemed like too much work, so I just made it a standard practice to always close my connections after each use.

Connections stay in a connection pool -- I'm no whiz on that -- but if was curious about performance, I guess I'd keep that in mind, in terms of what it costs to open a connection multiple times -- whatever your situation is requiring anyway.

Another thought is that your DB admin may be able to force-close all open connections, or the db may close for some other reason. If you're not the dba, you might give a thought to risk/benefit of depending on something that you don't have long-term control over like keeping the connection open.

stack traces stop before getting to my code (on Android using NDK)

7 votes

I'm developing on Android 2.3.x using NDK r5b. Occasionally my code crashes and I'd like to know where. I already know how to get the corresponding line in my application when I have a have a pointer (i.e. from Android's stack traces.)

However, oftentimes I see useless stack traces like this (full stack trace):

     #00  pc 0006561a  /system/lib/egl/libGLESv2_adreno200.so
     #01  pc 0006b900  /system/lib/egl/libGLESv2_adreno200.so
     #02  pc 0005aac8  /system/lib/egl/libGLESv2_adreno200.so
     #03  pc 0001687a  /system/lib/egl/libGLESv1_CM_adreno200.so
     #04  pc 000096ce  /system/lib/egl/libGLESv1_CM_adreno200.so

or this:

(gdb) bt
#0  0xafd0c51c in epoll_wait () from /Volumes/SecureCode/webos/rta/android/obj/local/armeabi/libc.so
#1  0xa81216a6 in ?? ()

that don't even mention my code at all.

Is there any way at all to get better stack traces than this? Why are some library functions "opaque" in that they don't allow the backtrace to "see through" to the calling function, causing a stop in the stack trace?

As far as I can tell, the only way to debug a problem like this is to use logging at each point in the program and/or step through each line with gdb.

Are there ROMs available with debug versions of these Android libraries instead of runtime ones, and would that help? (I use one phone solely for development, so I'm not concerned about keeping full functionality.) (Actually, I noticed that the path to libc.so in the above gdb stack trace is within my application directory. Could I possibly just package it with a different (debug) libc.so, and would that help?)

One last thing that might help: in the above stack trace from logcat (the first one,) my library is mentioned in the raw stack dump:

stack:
  ...
  ...
  4471cb88  00000028  
  4471cb8c  afd4649c  
  4471cb90  80b4eb71  /data/data/com.audia.dev.rta/lib/librta.so
  4471cb94  00299180  
  ...
  ...

but that is not a function pointer. What could that be, and would it be of any help after the app has crashed? I'm guessing probably not if it's a heap pointer or something like that.

Is there any way at all to get better stack traces than this?

As far as I know, you must build and write the Android image by yourself. It enables you to have the whole complete symbols of the Android (executable files and shared libraries) except proprietary shared libraries.

Also it provides to use the symbols using gdb.

$ adb shell setprop debug.db.uid 32767
$ adb forward tcp:5039 tcp:5039

/*
 program terminated and debuggerd caught exception like the following.
 Use the PID number for gdbclient 3rd parameter.
 I/DEBUG   ( 2154): ******************************************************** 
 I/DEBUG   ( 2154): * Process 2508 has been suspended while crashing.  To
 I/DEBUG   ( 2154): * attach gdbserver for a gdb connection on port 5039:
 I/DEBUG   ( 2154): *
 I/DEBUG   ( 2154): *     adb shell gdbserver :5039 --attach 2508 &
 I/DEBUG   ( 2154): *
 I/DEBUG   ( 2154): * Press HOME key to let the process continue crashing.
 I/DEBUG   ( 2154): ********************************************************)
*/

$ gdbclient "" "" 2508

EDITED:

You can still use ndk-gdb instead of gdbclient command. Please specify the symbol files for shared libraries.

(gdb) set solib-search-path (ANDROID_SOURCE_PATH)/out/target/product/(PRODUCT_NAME)/symbols/system/lib

EDITED 2:

If you don't need the symbols of the Android system shared libraries, just adb pull shared libraries and set sollib-search-path to it.

$ adb pull /system/lib lib

$ ndk-gdb
...
(gdb) set solib-search-path lib

RecognizerIntent: how to add a bundle to a pending intent

7 votes

I am implementing an activity that responds to the RecognizerIntent. Among others this activity must handle two incoming extras that specify a pending intent and its extras-bundle:

  • EXTRA_RESULTS_PENDINGINTENT
  • EXTRA_RESULTS_PENDINGINTENT_BUNDLE

Paraphrasing the documentation:

  • If you use EXTRA_RESULTS_PENDINGINTENT to supply a PendingIntent, the results will be added to its bundle and the PendingIntent will be sent to its target.

  • If you use EXTRA_RESULTS_PENDINGINTENT to supply a forwarding intent, you can also use EXTRA_RESULTS_PENDINGINTENT_BUNDLE to supply additional extras for the final intent. The search results will be added to this bundle, and the combined bundle will be sent to the target.

I have been looking in vain for sample code that would demonstrate the following.

What is the best way of extracting a PendingIntent from a bundle?

Should I do:

(PendingIntent)
        extras.getParcelable(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT)

How to add extras to the set of existing extras of a PendingIntent?

How to launch the modified PendingIntent?

These are my current answers to these questions. It works like this in a number of Google apps (Maps, Docs, YouTube, Listen) which all pass the PendingIntent to the RecognizerIntent when you perform the search via the microphone button. I am unsure though if this is the best (or most general) way of doing it. Any comments are welcome.

What is the best way of extracting a PendingIntent from a bundle?

Parcelable extraResultsPendingIntentAsParceable =
           bundle.getParcelable(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT);
if (extraResultsPendingIntentAsParceable != null) {
    if (extraResultsPendingIntentAsParceable instanceof PendingIntent) {
        mExtraResultsPendingIntent =
                         (PendingIntent) extraResultsPendingIntentAsParceable;
    } else {
        // Report an error
    }
}

mExtraResultsPendingIntentBundle =
          bundle.getBundle(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE);

How to add extras to the set of existing extras of a PendingIntent?

Here we just create a new intent and put all the required extras into it.

if (mExtraResultsPendingIntentBundle == null) {
    mExtraResultsPendingIntentBundle = new Bundle();
}               
Intent intent = new Intent(); 
intent.putExtras(mExtraResultsPendingIntentBundle);
// Unsure about the following line...
// Should I use another name for the extra data (instead of SearchManager.QUERY)
intent.putExtra(SearchManager.QUERY, speechRecognitionResult);

How to launch the modified PendingIntent?

We send off the PendingIntent giving it the new intent (with the new extras) as an argument.

try {           
    mExtraResultsPendingIntent.send(this, 1234, intent);
} catch (CanceledException e) {
    // Handle exception
}

Proper Way of Handling an Orientation Change in Android

7 votes

What is the proper way of handling an orientation change in Android? When I researched this question there are two methods that came up.

1st Method Use the methods onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) to store and restore your Activity after being killed by the Android OS after the orientation change.

2nd Method Added android:configChanges="orientation|keyboardHidden" to your AndroidManifest.xml so the Activity will not be destroyed when the orientation is changed.

I have tried both methods and they both work, however the first method takes a lot longer to implement. While I do see posts about the 2nd method, I want to know if this is an "accepted" and "proper" way of handling an orientation change. And what are the advantages and disadvantages for each method? Thanks!

The 1st method you mentioned is the proper way to do it (using bundles to pass data between new and old instances). The second option you listed is a hack for the most part.

There is one other way which isn't mentioned, and that's by onRetainNonConfigurationInstance.

Here's a bit more info on that method: http://developer.android.com/resources/articles/faster-screen-orientation-change.html

Edit: Be careful using this method though, it can cause memory leaks and similar issues if not done properly.

Eclipse AndroidManifest.xml format

6 votes

When I format the xml using Ctrl+Shift+F the result is being like that:

This is the result of Ctrl+Shift+F

But It would be nice if something can make xml like that:

But I want to have this

Is there any way to format the formatting on eclipse?

THIS could help

How to get the selected index of a RadioGroup in Android.

5 votes

Is there an easy way to get the selected index of a RadioGroup in Android or do I have to use OnCheckedChangeListener to listen for changes and have something that holds the last index selected?

example xml:

<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <RadioButton android:id="@+id/radio1" android:text="option 1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio2" android:text="option 2" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio3" android:text="option 3" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio4" android:text="option 4" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio5" android:text="option 5" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RadioGroup>

if a user selects option 3 I want to get the index, 2.

You should be able to do something like this:

int rbid = rbgrp.getCheckedRadioButtonId();
View rb = rbgrp.findViewById(rbid);
int idx = rbgrp.indexOfChild(rb);