Best android questions in March 2011

Running a Haskell program on the Android OS

27 votes

Forenote: This is an extension of the thread started on /r/haskell

Lets start with the facts:

  • Android is one awesome Operating System
  • Haskell is the best programming language on the planet

Therefore, clearly, combining them would make Android development that much better. So essentially I would just like to know how I can write Haskell programs for the Android OS. My question is:

How can I get a Haskell program to execute/run on the Android OS?

P.S. Ignore the jokes above because this is an honest question and I really would like to see this happen.

How you do it is by first getting a Haskell compiler which can target C with the android NDK which comes with a GCC port for ARM architectures. JHC can trivially do this with a very small inf style file which describes platform (word size, c-compiler, etc) I've done this with the Wii homebrew dev kit and it was quite easy. However jhc still has some stability issues with complex code such as using a monad transformer stack with IO but jhc has been improving a lot over the last 6 months. There is only one person working jhc I just wished more people could help him.

The other option is to build an "unregistered" port of GHC targeting ndk gcc, this is a lot more involved process because GHC is not a true cross-compiler at the moment and you need to understand the build system what parts you need to change. Another option is NHC which can cross-compile to C, like GHC you need to build nhc targeting a C compiler, NHC does not have many Haskell extensions like GHC.

Once you have Haskell compiler targeting NDK GCC, you will need write bindings to either android NDK JNI glue code framework (android 2.3) or you must write JNI glue code between Java-C-Haskell, the former option is the easier solution and if I remember correctly might actually be backwards compatible with Android 2.*

Once you have this you must build Haskell code as shared library or static library which gets linked into the NDK java glue code (which itself is a shared library). As far as I'm aware you can not officially run native executables on android. You could probably do it with a rooted phone, thus I assume this means you can not distribute native executables on the app store even when the NDK gcc port can generate native executables just fine. This also probably kills the option for using LLVM unless you can get the NDK JNI working with LLVM

The biggest hurdle isn't so much getting a Haskell compiler for android (which is still a big hurdle) the biggest problem is that some one needs to write binding APIs for NDK libraries which is a huge task and the situation is worse if you need to write android UI code because there are no NDK APIs for this part of android SDK. If you want to do android UI code in Haskell somebody will have to write Haskell bindings to Java through JNI/C. Unless there is a more automated process to writing binding libraries (and I know there are they are just not automated enough for me) then chances of some one doing it are quite low.

Compatibility lib, fragments, activated, and a headache

19 votes

In Android 3.0, the concept of "checked" can be rendered using an "activated" background. This gives you the persistent bar you see when you tap on a list fragment, providing context for the fragment to the list's right (e.g., tapping on a folder in Gmail highlights that folder and opens up another list fragment to show the conversations in that folder).

For example, the fragment samples show stuff like:

setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

That resource (android.R.layout.simple_list_item_activated_1) is new to Android 3.0. What makes it "activated" is:

android:background="?android:attr/activatedBackgroundIndicator"

That attribute value is new to Android 3.0 and will cause you to crash if you try using it on earlier versions of Android, from what I can tell. I want to set the background to this magic value for the 3.0/large/landscape combination, and skip it otherwise.

I can accomplish this by having two separate versions of the layout, one in a -v11 resource set, one in a regular resource set. This is a bit less DRY than I'd like, though, since the bulk of the layout is the same, with only this one attribute either being included or being skipped.

I took a stab at trying to use drawable resource aliases, so the android:background could refer to the alias and the alias would handle the -v11 differentiation, but <bitmap> drawables don't seem to like android:src="@null".

I suspect there's a styles-and-themes approach to this problem, but since I've never fully wrapped my head around those (one of my more embarrassing Android knowledge gaps), I'm not completely sure what to do.

Has anyone worked out a pattern for using "activated" on 3.0 and skipping it on pre-3.0, beyond separate layouts?

Thanks!

Styles are your friend....

Have two values directories, one is values-v11, the other the default values.

Each values directory contains a styles.xml, the difference being that the default values one contains;

<style name="listViewActivatedStyle"/>

The values-v11 contains;

<style name="listViewActivatedStyle">
   <item name="android:background">?android:attr/activatedBackgroundIndicator</item>
</style>

Then you can have a single layout which uses;

style="@style/listViewActivatedStyle"

and the appropriate one is selected.

Use camera flashlight in Android

15 votes

Hi all

I'm trying to use the cameras LED flashlight in a widget. I've found several threads about this topic (i.e. the one mentioned later..) , now I'm trying to control the light using:

Camera cam = Camera.open();     
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.release();

In the AndroidManifest.xml tried different permissions, currently I have:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.flash" />

I'm testing this on my Galaxy Tab as I don't have any other Android devices at hand: the light does not turn on. So I have a few questions now:

  1. Is there any way to test the led light behavior in the Emulator?
  2. Am I doing something wrong here?
  3. According to this question which deals with the same problem, it works differently on the Galaxy Tab. How?
  4. And finally, if it does work differently, I'm starting to wonder if it's just the Galaxy Tab or if other devices use different methods too. It would be hard to test then and it seems rather odd to me.

Thanks for any insight!

By the way, I quickly tested with quick-settings which gets mentioned a few times here. The flashlight doesn't work with quick-settings either.

Note that the Galaxy Tab stil uses android 2.2. I see there were some changes between 2.2 and 2.3.

Comment: I know it has to work somehow as I have found other apps in the market that work perfectly with the Galaxy Tab.

Comment 2: If I set cam.setParameters(p); and directly ask the camera for the current state with getFlashMode() it correctly returns FLASH_MODE_TORCH. However, if I release the camera and re-open it, it returns FLASH_MODE_OFF. It's almost as if the Camera object aknowledges the request but doesn't really pass it on to the hardware!?

--

After Konstantins comment, I removed the cam.release(); part. He is right, the settings are not persisted if you release the camera. If you use cam.open() again, you will get a fresh instance with the light off. The light's still not working on the galaxy tab though. So, I guess it's hard to keep the light on if you're trying to control it through a widget then. As soon as the background service is finished, the camera object is released automatically and therefore the light switches off again. My questions still remain, especially why the camera doesn't switch on in the first place.

Every device is a bit different. Samsung especially likes to make things complicated for app developers.

On the Galaxy Tab you should be good with:

Camera cam;
void ledon() {
    cam = Camera.open();     
    Parameters params = cam.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_ON);
    cam.setParameters(params);
    cam.startPreview();
    cam.autoFocus(new AutoFocusCallback() {
                public void onAutoFocus(boolean success, Camera camera) {
                }
            });
}

void ledoff() {
    cam.stopPreview();
    cam.release();
}

If that doesn't work then it might be a matter of setting FLASH_MODE_OFF initially and changing it after the startPreview.

Android: how can i improve the look of an app?

13 votes

I've seen that standard Android UI components have a poor look and feel.

Can you suggest me some links/suggestions to improve the look of an Android app?

Some ideas:

  1. LayoutAnimations for your ListViews.
  2. Using TextSwitcher and ImageSwitcher instead of TextView and ImageView.
  3. Add animations to your views.
  4. Provide the correct resources for every device. You can use android-ui-utils.
  5. Use android-wheel for iphone like pickers.
  6. Provide some android patterns with GreenDroid.
  7. Use rounded corners for your ListViews.
  8. Check the third party libs available.
  9. Internacionalize your app using android2po or getlocalization.
  10. Use mapviewballoons for your android map.
  11. If you have some sort of tutorial, place it inside a SwipeView.

PS: If you want your login to be secure, use naked-password for Android ;)

Common Errors while writing Android Project

12 votes

Hi,

What are the Common Errors come while creating Android Project.

  • Android Specific Error
  • Java Specific Error

If you know just include known error got by You.

Thanks.

Hi,

I will list some errors i m always getting.

  • NullPointer error

    1. when i use un initialized variable or object we are creating. (Java)
    2. when we use some layout out view that is not in xml what we set in context.(Android)


  • ClassCast Exception
    • when a program attempts to cast a an object to a type with which it is not compatible. (eg: when i try to use a linear layout which is declared as a relative layout in xml layout).


  • StackOverflowError
    • it can also occur in correctly written (but deeply recursive) programs.(java and android)
    • when a program becomes infinitely recursive.
    • we create layout (deep and complex) that exceeds that stack of platform or virtual machine . recursive or too much of layout will create Stack overflow error in Android
    • Too many inner layouts.


  • ActivityNotFoundException: Unable to find explicit activity class exception

    • The activity is not declared in manifest.


  • Android securityException
    • You need to declare all permission in the application Manifest that your application check this link (internet, access to contact,gps,wifi state,write to SDCard, etc).


  • OutofMemoryError
    • when a request for memory is made that can not be satisfied using the available platform resources . mainly using bit map, gallery , etc.


  • Application Not Responding (ANR)

    • Mainly comes when you are making network function,or some long process.

    this will block UI Thread so user can not do any work. to avoid ANR read this

This are thing i mainly get while creating Android Project.

Try to use Try - Catch block in All Place of program.
Use proper Naming conversion for all variable and ID's in Layout.


I read one article from net it contains some error now i am adding that alos if it have redundancy please forgive me.

Issue : My previously nice RelativeLayout is making an ugly heap or some elements aren't visible anymore...What's going on ??? I just moved an element in it... Solution : Never forget that in a RelativeLayout, elements are referenced and placed in relation to their neighbours. Maybe there is something wrong in the hierarchy of relationship between your element. Try opening the outline view in Eclipse and clicking each element to see where there is a rupture.

Issue : Circular dependencies cannot exist in RelativeLayout Solution : You have probably written the same dependency in two different way. For instance an ImageView as the attribute android:layout_toRightOf a TextView and the TextView has android:layout_toLeftOf the ImageView. Only one of them is necessary

Issue : I wrote a style for one of my view/layout, but when I apply it in my xml, I have no display in the layout viewer of Eclipse Solution : Unfortunately, this seems to be a bug of the android ADT, I reported it but no news so far. Anyway, no panic, styles are working well, but they aren't displayed properly in Eclipse. Just build the app and launch it on the emulator or phone and you will see if everything is fine or not.

Issue : Toast is written properly but nothing is displayed Solution : This is a common error of use : just add the .show() method to show the Toast and see if it is working well

issue : I tried to display a String from strings.xml but I just had a number like 0x7f060001 Solution : This is not a bug, just a display due to the way android deals with resources. When you want to retrieve a resource, you have to use a method like getString(R.id.something), getDrawable, …Otherwise, you just display the reference written in the R class

Issue : Some change in code doesn't have any effect in the application Solution : there are 2 options, either you have forgotten something like the .show() of the Toast, or the emulator is not updating properly your application. In that case, you have to check the option “Wipe user Data” in your launch configuration of the emulator in Eclipse.

Issue : How to display borders on my table? Solution : There is no direct way to do that in android, you have to use a trick :http://www.droidnova.com/display-borders-in-tablelayout,112.html

Issue : the emulator is writing in japaneese withtout you having changed any parameter Solution : This happens sometimes, quite easy to fix, just long click in any EditText field, and change the input type to what you want

Issue : I can't get the Context Menu to appear in the emulator Solution : long click on emulator does not seem to register on every kind of view, you have to push the button in the center of the 4 directionnal arrows

issue : I'm following a tutorial about map route but I can't get it work, android does not find a package Solution : You might have been following a tutorial written for 1.5 SDK. At this time, there was a package to display route in android, but it was removed in the next SDK and is not available anymore. It just not possible anymore. There seems to be a trick with KML files but nothing official

Issue : Sending coordinates to the emulator gives wrong position Solution : ensure that you wrote the coordinate like 51.16548 and not 51,16548 nor 5116548

issue : Only the original thread that created a view hierarchy can touch its views. Solution : You must have tried to update a view content from another thread than the UI thread. 2 options to patch this : either create a handler in your UI thread and post your Runnable to this handler OR use the method runOnUIThread to run the lines of code that are doing the update

Issue : accessing localhost 127.0.0.1 doesn't work Solution : it works, you are just not doing it the right way : use 10.0.2.2

Thanks,

Ganapathy.C

Show AlertDialog in any position of the screen

12 votes

Hi, When we show an AlertDialog in android it shows in the center of the screen. Is there any way to change the position?

After searching in various post I have found the solution.

The code is posted below:

private CharSequence[] items = {"Set as Ringtone", "Set as Alarm"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

            if(item == 0) {

            } else if(item == 1) {

            } else if(item == 2) {

            }
        }
    });

     AlertDialog dialog = builder.create();
     dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
     WindowManager.LayoutParams WMLP = dialog.getWindow().getAttributes();


 WMLP.x = 100;   //x position
 WMLP.y = 100;   //y position

 dialog.getWindow().setAttributes(WMLP);

 dialog.show();

Here x position's value is pixels from left to right. For y position value is from bottom to top.

Reading multiple NFC tags simultaneously in Android

11 votes

The new 2.3.3 SDK includes improved NFC support, and I'd like to write an app that relies on this. Ultimately, I'd like to be able to read data from multiple tags that enter the field simultaneously, but Android only seems to trigger on the first one that enters the field - subsequent ones are ignored.

From reading the NFC spec (ISO/IEC 14443-3) for the tags I'm using (Mifare Classic), I should be able to send a 'halt' command to the tag, which will cause it to stop responding, and allow me to read the next tag in the field. Android doesn't support the halt command directly on any of the TagTechnology subclasses, so I tried sending it myself directly using transceive(new byte[] {0x50, 0x00}). This throws an IOException, with the message 'transceive failed'.

Admittedly I'm doing all this from the main thread, which I understand is a bad idea, but I just want to test the concept as easily as possible.

Is it possible to communicate with multiple tags in the field at the same time? What am I doing wrong?

What you want is unfortunately not possible at the moment, unless you do some pretty advanced hackery, which is almost never a good idea :)

Probably you could halt the card if you send the right bytes in the transceive(), as you're trying to do now. But since the halt (or rather, the HLTA which you're trying to send) is an ISO14443-3A command, this will not work through the MifareClassic interface - which uses an "encrypted" pipe. Directly transmitting over the NfcA interface unfortunately doesn't work with the current stack either.

Even if you could get the card to halt, this will not automatically cause the NFC chip in the phone to resume polling for new tags - since you are "going around" the stack.

Targeting/Developing for multiple mobile platforms with one programming language (C#)? Cost-Benefit?

11 votes

Today it is possible to use C# programming for multiple mobile platforms such as:

(feel free to edit if I missed some) Of course, it is still programming effort for UI, but main libraries of app can be shared.

We can all thank to a team gathered around Mono project and superhero Miguel de Icaza whose effort is priceless.

What bothers me is, what are the benefits of these options? Is it cost of maintaining one app across multiple mobile platforms less impediment then having to code each library separately for better performance. Learning curve of each language? Being Jack of All trades vs .NET Ninja

Or knowing that binaries of app programmed in native environment are less in size, maybe even optimized better and not to forget that you have to wait support of new platform os updates.

UPDATE: Obviously there is one more thing to consider and that is support. Since Novell is bought by Attachmate Group, all Mono team is laid off. However the core member of the team lead by Miguel De Icaza founded new company Xamarin which will reinvent Mono Mobile development tools from the scratch.

In my opinion, the big pro of using one single environment (i.e. C#/.NET) is code portability. And cool things like LINQ that, once you get used to it, you can't live without. However, the few mobile OS's (iOS, Android, WP7) are quite different with regards to UI.

And, if I am not mistaken about your application, it's got a fair share of UI interactions if it is to run on a mobile device. Most mobile apps are like 80% UI code.

Therefore, you'll end up writing a separate set of UI code for each platform anyway -- for example, you'll be writing in Silverlight WP7 (and all the WPF goodness), you'll be writing a completely different set of code for iOS in Cocoa (IB, Views, controllers and stuff), you'll be writing yet a completely different set of code for Android.

My experience has always been that it take a lot of experience to write good UI code on any platform -- e.g. learning WPF/SL is already the nightmare that is, throw in Cocoa Touch and the whole Android mess. Of course you can write three sets of UI that look and feel reasonably similar, but chances are that you'll be trying so hard to reuse code and have common data structures that your UI's will end up sub-par when compared to dedicated apps -- and in this cut-throat world of mobile apps today, a non-super (not to mention sub-par) UI experience means death to your app.

Also, all three mobile environments have different connectivity paradigms, as well as multimedia paradigms. You end up writing three versions, and learning three environments, albeit writing in one language you're familiar with.

The most you're going to reuse is back-end modules. Decision engines, search routines, data-management etc. And even these are going to be problematic because you'll be force to have compromises in your data structures just to enable easy integration with three different sets of UI code working on three different UI paradigms. For example, do you use DependencyObjects for use to bind to Silverlight views in an MVVM model? If you do, it won't work with Cocoa's MVC model, and you have to code those bindings separately.

And since not all mobile environments enable you to use the full set of functionalities -- for example, MonoTouch for iOS does not generic constructs that cannot be determined at compile time. You're essentially using a very small subset of .NET (and must constant be reminding yourself what functionality can be used where) just so that you can run them all on three different platforms without significant changes.

Now image having all these limitations when you are writing for the WP7 platform, which supports the entire .NET features set. I don't know about you, but I'll go crazy. And your WP7 app is never going to be even close to being competitive with other apps out there.

In my opinion, the pain and the compromises are not worth it. You'll end up with three so-so apps, which people in neither of the platforms are going to like.

Unless all the goodness lies in your app's back-end logic, and it is so good that people are going to ignore UI issues just to get to your app's back-end functionalities. In my experience, this almost never happens.

Android HttpClient OOM on 4G/LTE (HTC Thunderbolt)

11 votes

I have gotten some reports from users of crashes when try use my application on Verizon's 4G/LTE.

Looking at the stack trace, it looks like Android's HttpClient.execute() implementation is throwing an OOM. This happens only on 4G/LTE devices, specifically HTC Thunderbolt, and only when on 4G/LTE. WiFi, 3G, UMTS are OK. Also works fine on Sprint's WiMax 4G stuff works fine.

Two questions:

  • What's the best way to get the attention of Android devs about this? Any better options than reporting on http://code.google.com/p/android/issues?

  • Any ideas on how I can work around this? I don't have a 4G device myself and I can't get this happen in the emulator so I need to make some educated guesses here. I can try to catch the OOM in my code and attempt to cleanup and force GC, but I'm not sure if that's a good idea. Comments or other suggestions?

Here's what my code's doing:

    HttpParams params = this.getHttpParams(); // returns params
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, this.getHttpSchemeRegistry() );
    DefaultHttpClient httpClient = new DefaultHttpClient( cm, params );

    HttpResponse response = null;
    request = new HttpGet( url );

    try {

        response = httpClient.execute(request); // <-- OOM on 4G/LTE. OK otherwise
        int statusCode = response.getStatusLine().getStatusCode();
        Log.i("fetcher", "execute returned, http status " + statusCode );

    ...

Here's the crashing stack trace:

E/dalvikvm-heap(11639): Out of memory on a 2055696-byte allocation. I/dalvikvm(11639): "Thread-16" prio=5 tid=9 RUNNABLE I/dalvikvm(11639): | group="main" sCount=0 dsCount=0 s=N obj=0x48563070 self=0x3c4340 I/dalvikvm(11639): | sysTid=11682 nice=0 sched=0/0 cgrp=default handle=3948760 I/dalvikvm(11639): | schedstat=( 208709711 74005130 214 )

I/dalvikvm(11639): at org.apache.http.impl.io.AbstractSessionInputBuffer.init(AbstractSessionInputBuffer.java:~79) I/dalvikvm(11639): at org.apache.http.impl.io.SocketInputBuffer.(SocketInputBuffer.java:93) I/dalvikvm(11639): at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:83) I/dalvikvm(11639): at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:170) I/dalvikvm(11639): at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:106) I/dalvikvm(11639): at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129) I/dalvikvm(11639): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:173) I/dalvikvm(11639): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) I/dalvikvm(11639): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) I/dalvikvm(11639): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348) I/dalvikvm(11639): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) I/dalvikvm(11639): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) I/dalvikvm(11639): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) I/dalvikvm(11639): at com.myapplication.Fetcher.trySourceFetch(Fetcher.java:205) I/dalvikvm(11639): at com.myapplication.Fetcher.run(Fetcher.java:298) I/dalvikvm(11639): at java.lang.Thread.run(Thread.java:1102) I/dalvikvm(11639): E/dalvikvm(11639): Out of memory: Heap Size=24171KB, Allocated=23142KB, Bitmap Size=59KB, Limit=21884KB E/dalvikvm(11639): Extra info: Footprint=24327KB, Allowed Footprint=24519KB, Trimmed=348KB W/dalvikvm(11639): threadid=9: thread exiting with uncaught exception (group=0x40025b38)

Looking at the stack trace, it looks like Android's HttpClient.execute() implementation is throwing an OOM.

That is not indicated by the stack trace you have on the issue. Of course, you didn't provide the whole stack trace on the issue.

What's the best way to get the attention of Android devs about this? Any better options than reporting on http://code.google.com/p/android/issues?

The odds of this being a pure Android bug are small, though not zero.

Here are some other possibilities, in no particular order:

  1. There is no problem with execute() per se, but that you are simply running out of memory, and the stack traces you have encountered are simply demonstrating that execute() is stressing your heap.

  2. The problem is in some modifications that HTC made to Android for the Thunderbolt, possibly only taking effect when on the LTE network.

  3. The problem is somehow caused by the Verizon LTE network itself (e.g., some proxy of theirs sending back screwball information that is causing HttpClient to have a conniption).

Any ideas on how I can work around this?

First, I'd use existing tools (e.g., dumping HPROF and examining with Eclipse MAT) to confirm that you don't have a memory leak in general that the Thunderbolt/LTE combo just seems to be tripping over.

Next, I recommend that you come up with some way to consistently reproduce the error. That could be your existing app with a series of steps to follow, or it could be a dedicated app (e.g., log the URL that triggers the OOM, then create a tiny app that just does that HttpClient request). I wish DeviceAnywhere had a Thunderbolt, but it doesn't look like it. I'll put some feelers out and see if I can get some help on that front.

In terms of working around it, as a stopgap, you can detect that you're running on a Thunderbolt via android.os.Build data, and perhaps that you're on LTE via ConnectivityManager (I'm guessing LTE would list as WiMAX, but that's just a guess), and warn users about the problems with that combo.

Beyond that, you can try changing up your HttpClient usage a bit and see if it has an effect, such as:

  • If you are only supporting API Level 8 or higher, you could give AndroidHttpClient a shot as a drop-in replacement
  • Disable multi-threaded access (in general or Thunderbolt-specific) and get rid of the ThreadSafeClientConnManager

I'm sorry that I don't have a "magic bullet" answer for you here.


UPDATE

Now that I have the full stack trace, looking through the source code is...illuminating, somewhat.

The problem appears to be that:

HttpConnectionParams.getSocketBufferSize(params);

is returning that 2MB or so value that is triggering the OOM. That's an awfully big buffer, particularly for the Dalvik GC engine, which can get fragmented (yes, there's that word again).

params here is the HttpParams. You seem to be creating those yourself via getHttpParams(). For example, AndroidHttpClient sets that to 8192:

HttpConnectionParams.setSocketBufferSize(params, 8192);

If you are setting the socket buffer size yourself, try reducing it. If not, try setting it to 8192 and see if that helps.

Display input validation errors in popup.

9 votes

I want to show all my validation error's of EdiText fields in a popup as shown in below image:

Error alert in popup

As far as I know Android has drawables:

1) popup_inline_error.9.png

popup_inline_error.9.png

2) popup_inline_error_above.9.png

popup_inline_error_above.9

3) indicator_input_error.png

indicator_input_error.png

I am able to display the red error indicator inside the right side of the EditText by using:

Drawable err_indiactor = getResources().getDrawable(R.drawable.indicator_input_error);
mEdiText.setCompoundDrawablesWithIntrinsicBounds(null, null, err_indiactor, null);

Now also i want to display the error message as shown is the first image but it seems I am not getting any idea about this, though I think it should be a Custom Toast.

try this..

final EditText editText=(EditText) findViewById(R.id.edit);

 editText.setImeActionLabel("",EditorInfo.IME_ACTION_NEXT);

        editText.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId==EditorInfo.IME_ACTION_NEXT){
                    if( editText.getText().toString().trim().equalsIgnoreCase(""))
                        editText.setError("Please enter some thing!!!");
                    else
                        Toast.makeText(getApplicationContext(),"Notnull",Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });

Cost of raising an Intent in android

9 votes

How much performance does it costs to broadcast intents? Is it okay to broadcast multiple per second or are intents expensive?

Intents are meant to launch different activities within the Android OS or to inform about basic actions. It seems like a bad design pattern to use them otherwise. As they travel between different processes and therefore implement the Parcelable interface, they are not the most light-weight.

If you are looking to update different activities at the same time you might consider using a common service.

According to this blog post, intents are 10 times slower than direct function calls http://andytsui.wordpress.com/2010/09/14/android-intent-performance/

Weird performance issue with Galaxy Tab

8 votes

I am working on a 2d tutorial and was able to test my current tutorial part on a Samsung Galaxy Tab.

The tutorial simply moves the default icon randomly over the screen. With a tap I create a new moving icon. Everything works fine (constantly 60fps) on the Galaxy as long as I have 25 elements or less on the screen.

With the 26th element the frame rate drops to 25fps.

When I change the size/dimension of the image to a much bigger one, I reach less than 25fps before the 26th element. Thats ok. But at some not really reproducible number of elements the frame drops from (mostly more than) 10fps to 1fps.

On my Nexus One I can add 150 elements and still have 50fps.

What I have done: I changed the bitmap variable to a static one, so not every element has his own image but all use the same. That removed the behavior, but I doubt this solution is a good one. The magic number of 25 would suggest that I can use only 25 different images in that way.

Does someone have any idea what can cause this behavior? Is it a bug in the modified android version of Samsung?

My sample eclipse project is available. I would appreciate if some Samsung owner would check their performance with the sample.

edit

A colleague found a solution. He changed the way the bitmap is loaded from

mBitmap = BitmapFactory.decodeResource(res, R.drawable.icon);

to

mBitmap = BitmapFactory.decodeStream(new BufferedInputStream(res.openRawResource(R.drawable.icon)));

But we still don't really get it why it works this way...

Well, I've been looking on your project and everything seems to be fine, but I have one idea about what's causing you the frame rate drop.

You're allocating objects during runtime. If you don't do that, it will make you create all objects at start, and therefore you should notice a significant drop directly (if my solution doesn't solve your problem).

That said; I'm not sure whether an object pool will solve your problem, but you can try. Initialize your objects in a constructor and instead of making this call in onTouchEvent():

new Element(getResources(), (int) event.getX(), (int) event.getY())

You should have something like mElement.add(objectPool.allocate()), where the object pool finds an unused object in the pool. Also, we should have a specified amount of objects in that object pool and from there you can check if it is the allocating that is causing this error or if it is something else.

With the 26th element the frame rate drops to 25fps.

When (or if) you implements this, you should see the frame rate drop directly (if this doesn't solve your problem though), since the object pool will make you allocating a fixed amount (e.g. maybe 100 elements?) at start (but you're not using them visually).

Also, I have used the memory pool pattern (object pool) in one of my sample applications for Android. In that sample; I add a line to the Canvas on an onTouchEvent() using an object pool (without allocating during runtime). In that source code you can easily change the total amounts of objects and check it out and try it yourself. Write a comment if you want to look at my sample application (and source code) and I will gladly share it since it's not public yet. My comments are in swedish, but I think you should be able to understand, since the variables and methods are in english. :)

Side note: You wrote that you've tried (and even success) with removing the behaviour by making your Bitmap static. As it is right now, your elements have different instances of a Bitmap, which will make you allocate a new Bitmap everytime you're constructing a new object. That means that every object is pointing to a different Bitmap when they are using the same resource. static is a fully valid solution (although a magic number of 25 seems wierd).

This Bitmap case can be compared to the OpenGL system. If you have 20 objects which all should use the same resource, there are two possible solutions: They can point to the same VRAM texture or either they can point to a different VRAM texture (like your case when you're not using static), but still same resource.

EDIT:

Here is my sample application for Android that demonstrates the Memory Pool.

Regarding your solution with BitmapFactory, that's probably depending on how that class works. I'm not sure, but I think that one of the decode...() methods generates a new Bitmap even if it is the same resource. It can be the case that new BufferedInputStream(res.openRawResource(R.drawable.icon)) is reusing the BufferedInputStream from memory, although, that is a big guess.

What you should do (in that case) is to decode a resource and store a reference from it in the Panel class and pass that reference into the new Element(bitmapReference, ...) instead. In that way, you're only allocating it once and every element is pointing to the same Bitmap in memory.

Mobile App - Targetting iPhone, WP7, Android, and Blackberry

8 votes

Is there a sane way to develop a cross platform Mobile app? We want these to be native apps on each platform, and not necessarily some kind of web page.

Currently we're thinking to split it into two languages:

  • C# backend (business logic)
  • --> Standard C# app for WP7
  • --> App built on MonoTouch for iPhone/iPad/etc.
  • Java backend (business logic)
  • --> Standard Android Java app (MonoDroid version of C# not ready yet)
  • --> Standard Blackberry Java app

We could also develop initially in C# and use one of the conversion tools out there to get our C# converted into Java as a starting point.

Is there another approach? Our skillsets include mainly include a strong C# .Net background, and minor Java experience.

We don't really want to go low level and use something like C/C++ to get the job done. These are usually going to be simple LOB applications that communicate to some web service.

Side Question: how do game devs like the makers of Angry Birds do it?

UPDATE:

MonoDroid is now officially released. So it seems you would only need to use Java for the BlackBerry. We are considering not developing for BlackBerry at all, because developing for the other 3 platforms has been simplified. There is definitely some cost involved, as MonoTouch and MonoDroid are both $399 and you would also need a license for Visual Studio (this doesn't include cost for App store, etc.).

There's no good simple answer that I know of for all mobile platforms. You can use development environments like Appcelerator Titanium, which cross-compile to native code on various platforms (right now, for instance, I think Titanium supports iOS and Android, with plans for Blackberry). However, these usually have a limited API that you have access to, and you still end up needing to design different UIs for the different platforms (in my commercial work, I have never successfully used such a platform)

You could also design all the business logic in a web-services back end, and then just write "thin client" apps for each platform. This works, but of course requires network access when the end user wants to use your app. (Usually it'll be there, but sometimes may not)

Ultimately, I usually end up doing what you propose -- writing the basic business logic in a couple of different languages as generically as possible, and then bundling that in with custom UI/device code for each platform. Haven't found a better way myself....

(BTW, I believe games like Angry Birds are written largely in OpenGL and then loaded onto the OpenGL processor on each platform. But I could be mistaken...)

Android XML layout files and namespace

7 votes

Android layouts are defined in XML with this namespace declared in the root element:

xmlns:android="http://schemas.android.com/apk/res/android"

Example of an element:

<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" />
  1. Why is the android prefix used instead of ommitting it like xmlns="http... ?
  2. Why is the prefix used only in attributes and not in elements?

Interesting question! it sure feel a bit weird.

  1. It was a design choice by Google to be as strict as possible on namespace to handle errors at compile time.
  2. The prefix is not used on elements because theses are representing Java classes: com.android.widget.TextView (com.android.widget.* can always be truncated). The java namespace of this class will be automagically resolved at compile time, so an xml namespace representing a fully qualified java namespace is not welcome here. But attributes can be mapped to any of the inherited java classes of the Element. Hence the namespace on attributes to allow inheritence.

This is done like this mainly because the layout describes Java objects and Google here is using the XML namespace mechanism to help mapping your Layout with Java objects. So there are collisions between the Java namespace world and XML namespace world. It also allow us developers to subclass elements, add our own attributes without worrying that the next version of the plateform will maybe add an attribute with the same name.

See the two replies to this blog post by Dianne Hackborn, a well-known android engineer working at google: http://www.elharo.com/blog/software-development/xml/2008/09/16/android-xml-weirdness/