Best android questions in July 2011

Starting the Android emulator in SDK tools, revision 12

23 votes

I updated the Android SDK tools from revision 11 to revision 12, and the emulator now fails to start. When I try to run emulator.exe, I get:

invalid command-line parameter: Files\Android\android-sdk\tools/emulator-arm.exe.
Hint: use '@foo' to launch a virtual device named 'foo'.
please use -help for more information

The path to emulator.exe is C:\Program Files\Android\android-sdk\tools.

How do I fix it?

As was previously suggested, it does seem to be caused by the fact that there is a space in the default installation path of the Android SDK: C:\Program Files\Android\android-sdk\

There are a couple of possible solves, though-

  1. move installation directories to paths that do not contains spaces (as already mentioned)...
  2. but simpler and possibly slightly less cumbersome is simply adjusting the path in Eclipse to use 8-dot-3 directory name(s). Since I'm running Win7, I have two Program Files directories, the second one being "Program Files (x86)" which is where the sdk installed. So the 8-dot-3 path is PROGRA~2. Thus, I simply changed the "SDK Location" value in the Android Preferences in Eclipse from C:\Program Files\Android\android-sdk\ to C:\PROGRA~2\Android\android-sdk\ and everything now works fine.

If you don't know the 8-dot-3 name of your desired path, just fire up a Command Prompt and execute "DIR /X"... the short name will be displayed next to each directory.

Running Android apps on web browser

16 votes

I work for company which specializes in Native mobile app development. The company does both Android and iOS apps. Now to show our apps to executives for different companies we use pieceable.com to embed our iOS apps in browser. This way we can just send these potential customer an url and they can play around with the app.

After searching internet for a long time I couldn't find anything to do that kind of functionality for an Android app. Is there a way I can do it. Are there any tools which I can use?

You could run the App in an instance of the Android emulator, a VM which is part of the free Android SDK.

Running the emulator in a regular VNC server session, rather than a VNC server App running on the emulator, would most likely provide better performance.

The VNC session and the Android emulator session could be started as needed from a web page with an embedded VNC viewer Java applet. On Ubuntu, for example, this is Java viewer client is freely available in the vnc-java package.

To avoid inadvertent data sharing between users, it would be necessary to run each VM session with a clean copy of the Android VM's AVD and virtual SD-card instance.

To reduce the VM copy and start-up time for the emulator sessions, it may be desirable to have the web server maintain a few active sessions started and ready for use. This would provide clean individual sessions for your potential customers to try.

TCP-based RPC server (Erlang or something similar?) for iOS/Android app communication

13 votes

I'm building native mobile applications in both iOS and Android. These apps require "realtime" updates from and to the server, same as any other network-based application does (Facebook, Twitter, social games like Words with Friends, etc)

I think using HTTP long polling for this is over kill in the sense that long polling can be detrimental to battery life, especially with a lot of TCP setup/teardown. It might make sense to have the mobile applications use persistent TCP sockets to establish a connection to the server, and send RPC style commands to the server for all web service communication. This ofcourse, would require a server to handle the long-lived TCP connection and be able to speak to a web service once it makes sense of the data passed down the TCP pipe. I'm thinking of passing data in plain text using JSON or XML.

Perhaps an Erlang based RPC server would do well for a network based application like this. It would allow for the mobile apps to send and receive data from the server all over one connection without multiple setup/teardown that individual HTTP requests would do using something like NSURLConnection on iOS. Since no web browser isn't involved, we don't need to deal with the nuances of HTTP at the mobile client level. A lot of these "COMET" and long-polling/streaming servers are built with HTTP in mind. I'm thinking just using a plain-text protocol over TCP is good enough, will make the client more responsive, allow for receiving of updates from the server, and preserve battery life over the traditional long polling and streaming models.

Does anyone currently do this with their native iOS or Android app? Did you write your own server or is there something open sourced out there that I can begin working with today instead of reinventing the wheel? Is there any reason why using just a TCP based RPC service is a worse decision than using HTTP?

I also looked into HTTP pipelining, but it doesn't look to be worth the trouble when it comes to implementing it on the clients. Also, I'm not sure if it would allow for bi-directional communication in the client<->server communication channel.

Any insight would be greatly appreciated.

Using TCP sockets with your own protocol rolled down is quite better than HTTP especially with the nature of resources on the mobile devices. Erlang will do quite well, however lets start from your protocol. Erlang excels well at this especially with the Bit Syntax expressions. However still, you could use plain text as you wish. JSON (would need a parser: Mochijson2.erl found in Mochiweb library) and XML (will need a parser: Erlsom).

I have personally worked on a project in which we were using raw TCP Sockets with our Erlang Servers and Mobile Devices. However, depending on the Port numbers you choose, Routers along the way would block/Drop packets depending on the security policies of service providers. However, i still think that HTTP can work. People chat on Facebook Mobile, send Twits e.t.c from their devices and am sure these social engines use some kind of Long Polling or Server Push or whatever but using HTTP. The mobile devices have advanced in capability of late.

Rolling your own TCP Based protocol comes with a number of challenges: Port selection, Parsing of data both at the client and server, Security issues e.t.c. Using HTTP will let you think of the actual problem than spending time correcting protocol issues at client or server. The Devices you've mentioned above like Android and IOS (Ipad, Iphone e.t.c) are very capable of handling HTTP COMET (Long polling). Am sure when you follow the standards for Web Applications on Mobile devices as well as these W3C Mobile Web Best Practices, your app will function well using HTTP.

Using HTTP methods will quicken the work and there are a lot of libraries on the SDKs of these Devices which would assist you prototype the solution you want as compared to the situation of rolling your own TCP-based plain text protocol. To back up this reasoning, look through these W3C findings.

Let me finally talk of the HTTP benefits on these Devices. If you are to use Web technologies for Mobile devices, such as Opera Widgets, Phone Gap, Sencha Touch, and JQuery Mobile, their SDKs and Libraries have Optimizations already done for you or have well documented ways in which your app can be made efficient. Further still, these technologies have the APIs to access the native Devices' resources like Battery check, SMS, MMS, GSM broadcast channels, Contacts, Lighting, GPS , and Memory; all as APIs in the JavaScript classes. It would become hard (inflexible) if you use native programming languages like J2ME, Mobile Python or Symbian C++ / Qt as compared to using Web technologies like CSS3, HTML5 and JavaScript tools mentioned above. Using the Web tools mentioned above will make your app easily distributable by say Ovi Store or Apple Store, from experience.

Take note that if you use HTTP, testing will be easy. All you need is a public Domain so the Widgets on the mobile device locates your servers over the Internet. If you role your own TCP/IP protocol, the Network Routers may be disruptive against the Port number you use unless you plan on using port 80 or another well known port, but then still your Server IP would have to be made Public. There is a short cut to this: if you put your TCP Server behind the same ISP as your testing Mobile's Internet connection, the ISP routers will see both source and destination as behind its Network. But all in all, there are challenges with rolling your own protocol.

Edit: Using HTTP, you will benefit from REST. Web Servers implemented in Erlang (especially Yaws and Mochiweb) excel at REST services. Look at this article: RESTFUL services with Yaws. For mochiweb, there is an interesting article about: A million User comet application using Mochiweb which is broken into 3 parts. Further still, you could look at the solution given to this question.

Map.clear() vs new Map : Which one will be better?

12 votes

I have a Map as syntax as Map<String, String> testMap = new HashMap<String, String>();. In this map there can be 1000 data.

When my application requires to new list of data, then I must clear the Map. But when I saw the code of Map.clear() as

/**
     * Removes all of the mappings from this map.
     * The map will be empty after this call returns.
     */
    public void clear() {
        modCount++;
        Entry[] tab = table;
        for (int i = 0; i < tab.length; i++)
            tab[i] = null;
        size = 0;
    }

I realize that clear method goes in loop for n times (Where n is number of data in Map). So I thought there can be a way to redefine that Map as testMap = new HashMap<String, String>(); and previously used Map will be Garbage collected.

But I am not sure this will be a good way. I am working on mobile application.

Can you please guide me?

Complicated question. Let's see what happens.

You instantiate a new instance, which is backed with new array. So, garbage collector should clear all the key and values from the previous map, and clear the reference to itself. So O(n) algorithm is executed anywhere, but in garbage collector. In case of 1000 records you won't see any difference. BUT. The performance guide tells you that it always better not to create new objects, if you can. So I would go with clear() method.

Anyway, try both variants and try to measure. Always measure!

Android: slow network during phone calls

11 votes

We're working on an app that streams a large amount of data out via UDP for GSM-based phones. The idea is to use it while in conjunction with a voice call. If no voice call is present, things are good. However, if a voice call is active, it seems that most of the data we're sending out simply never makes it, even on HSPA+. If we enable Wifi, then everything is good.

I'm worried that this is a physics problem, rather than a phone one. I ruled out CPU contention by inserting a log statement after we send a chunk of data, and saw that it appeared plenty of times.

Is the 3G radio capable of sending data and voice simultaneously well? We tried a speed test during a voice call and saw a huge drop in bandwidth.

I've run into exactly this problem on AT&T's network in the US. They simply throttle the bandwidth while the call is in progress; whether you're on 3G or H. To see how much you're getting throttled try installing speedtest.net's app and running a speed test during and outside a call.

In the bay area I see data rates as low as 30kbit/s during a call on AT&T's network. On T-Mobile it's not throttled so much (same location). A partner in Israel tried the same test and saw only slight throttling during a call -- he was still seeing 500+kbit/s using the same phone that we tested on in the US. (The same phone that got several Mbit/s outside a call in the US.)

As the poster above points out, CDMA phones can't use data concurrently with a phone call at all (but you said GSM explicitly in your post anyway).

Android 1.6 & Fragment & Tabhost

10 votes

I'm working on upgrading an Android application (1.6 compatibility) which uses a TabHost to show 3 different tabs with nested activities.

At the time I used the ActivityGroup trick to show nested activities in a tab but I'm very unhappy with this method since it's a real pain to handle some features.

I heard about the Fragments API compatibility package for 1.6 and a Fragment looks perfect for what I want to do (show nested views / features within a tab with transition effects and stuff) but I can't make it work with a TabHost (It was meant to work with an Action Bar but it's not available in the compatibility package).

Did any of you guys found a way to create such a structure in your applications?

My error here is :

ERROR/AndroidRuntime(955): Caused by: java.lang.RuntimeException: Unable

to start activity ComponentInfo{com.XXX}: java.lang.IllegalArgumentException: No view found for id 0x1020011 for fragment MyFragment

CODE

main.xml

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:layout_weight="1" />

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0" />

    </LinearLayout>

</TabHost>

MainActivity.java

public class MainActivity extends TabActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Resources res = getResources();
        final TabHost tabs = getTabHost(); 
        TabHost.TabSpec spec;
        Intent i;

        i = new Intent(this, MyActivity.class);
        spec = tabs.newTabSpec("MyActivity").setIndicator("MyActivity",res.getDrawable(R.drawable.tab)).setContent(i);
        tabs.addTab(spec);

    }

}

MyActivity.class

public class MyActivity extends FragmentActivity {

    private static String TAG = "MyActivity";
    private static FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        ListeResultatFragment fragment = MyFragment.newInstance();
        fragmentTransaction.add(android.R.id.tabcontent, fragment, "MyFragment");
        fragmentTransaction.commit();

    }

}

MyFragment.java

public class MyFragment extends Fragment {

    public static MyFragment newInstance() {
        MyFragment instance = new MyFragment();
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment, container, false);
    }

}

The problem is that your MyActivity tries to reach out to the enclosing MainActivity by using android.R.id.tabcontent as a container id. This is not possible. Instead, MyActivity needs to have its own layout (e.g. a FrameLayout) which can be used as the parent for the Fragment. In this layout, there must exist a view that can be referenced by id.

Let's say you have a layout called activity_layout.xml which contains a FrameLayout with the id 'framelayout'. You can then modify the onCreate method in MyActivity to something like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View parent = getLayoutInflater().inflate(R.layout.activity_layout, null);
    setContentView(parent);

    fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment fragment = MyFragment.newInstance();
    fragmentTransaction.add(R.id.framelayout, fragment, "MyFragment");
    fragmentTransaction.commit();
}

In other words, MyActivity needs to be able to work on its own. Try to make it work first, and then embed MyActivity in the MainActivity containing the TabHost.

Machine that can turn phone 90 degrees every few seconds?

10 votes

I want to detect memory leaks in my Android application. Some leaks could be detected while rotating the phone physically so that the activities are constantly recreated.

I'm looking of some sort of physical device that could turn the phone 90 degrees every X seconds. I could build something using lego Mindstorm (that would actually be very cool), but I'm looking for something cheaper.

I also thought of using a clock, but I couldn't find one that has a clock second hand strong enough. Futhermore if the phone rotate 360 degrees after some time the USB cable would become too twisted. I think a device that goes back and forth between horizontal and vertical would be perfect.

My dream testing machine would also allow me to plug a USB cable so that I can run the Monkey tool while constantly rotating the phone.

You need to trigger configuration change somehow. This might be orientation change, hardware keyboard is opened or hidden, or any other change listed here: android:configChanges.

And there is one way to change configuration without using physical approach. You can use "Car Mode" or "Night Mode". Both only work in Android 8+ and can be turned on/off using UiModeManager.

So you can write your custom Service that will periodically call UiModeManager.enableCarMode(0) and UiModeManager.disableCarMode(0);, which in turn will force configuration changes in your Activity under test.

How can I find out if a device has a vibrator?

8 votes

I have a device of which I don't know if it has a vibrator.

Is there a way to query for the availability of the vibrator?

The Vibrator class does just that. It's hasVibrator() method returns a boolean indicating if vibrating is supported.

  1. Get an instance of the Vibrator class which is a system service.
  2. Query the Vibrator class using the hasVibrator() method.
String vs = Context.VIBRATOR_SERVICE;
Vibrator mVibrator = (Vibrator)getSystemService(vs);

boolean isVibrator = mVibrator.hasVibrator();

How to create website APIs

7 votes

I get a lot of clients asking me about making mobile apps that connect to their websites to retrieve data, allow users to login, etc. Most of them have PHP-based sites, but don't have any clue about making APIs to interface with them. They ask me why I can't just connect directly to their SQL databases. I don't think that's a good thing to do from a mobile app. I would prefer they have some sort of API in place.

As far as PHP-based sites go, what are the best options when it comes to implementing an API for this purpose?

Thanks, gb

You want to look into RESTful web services. Have a look at the wiki for this here. Your client's need to essentially build PHP applications that serve the underlying data of their websites through some REST-compliant data type e.g. JSON, XML, SOAP, etc. There are a number of in-built PHP functions that enable the quick conversion of PHP data structures into these formats. This would enable you to build mobile apps that make HTTP requests to get data which it can then display in it's own unique way.

An example for a JSON powered service could be as follows:

$action = $_GET['action'];
switch($action) {
  case 'get-newest-products':
     echo json_encode(getNewestProducts());
     break;
  case 'get-best-products':
     echo json_encode(getBestProducts());
     break;
  .
  .
  .
  default:
     echo json_encode(array());
     break;
}

function getNewestProducts($limit = 10) {
  $rs = mysql_query("SELECT * FROM products ORDER BY created DESC LIMIT $limit");

  $products = array();
  if (mysql_num_rows($rs) > 0) {
    while ($obj = mysql_fetch_object($rs)) {
      $products[] $obj;
    }
  }
  return $products;
}

function getBestProducts($limit = 10) {
  $rs = mysql_query("SELECT * FROM products ORDER BY likes DESC LIMIT $limit");

  $products = array();
  if (mysql_num_rows($rs) > 0) {
    while ($obj = mysql_fetch_object($rs)) {
      $products[] $obj;
    }
  }
  return $products;
}

You could query the API as follows (with mod_rewrite on) http://myapi.mywebsite.com/get-newest-products

What does "category" in the manifest mean?

7 votes

http://developer.android.com/reference/android/content/Intent.html#addCategory(java.lang.String) says you can specify a custom category. When, why and how would you do it? What would be the use of it?

The way I understand it, categories are public directives to the android operating system(and other apps) that represent different categories that your app should be a part of.

Example

  • When the launcher icon is tapped on the home screen, the home application looks through every installed app's manifest for the HOME category -- and if so it displays it in the app drawer.

However, there's more. You can specify categories in your applications manifest that lets the system know that you application can handle the intent category. For example, by putting a ALTERNATIVE category, other apps in the system know that your app can handle that category without specifically knowing the action name! In the following example, custom intent categories are passed through this intent, which is filtered and the corresponding object gets edited(taken from the Notes example app):

<intent-filter android:label="@string/resolve_title">
 <action android:name="com.android.notepad.action.EDIT_TITLE" />
 <category android:name="android.intent.category.DEFAULT" />
 <category android:name="android.intent.category.ALTERNATIVE" />
 <category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
 <data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
</intent-filter>

By registering this intent filter in an <activity /> tag, you can edit a "note". The intent data would contain the note, and the intent would get routed to the activity that this filter is registered in.

In Conclusion:

There isn't really a reason you'd use a custom category. They are for Android, and thus do't really make sene in application use. But, if you choose to use them, they can be used in the methods described above. "They provide some specific semantic rules, and if those rules are useful to you then feel free to use them"(Hackbod).

Porting Java class and methods to Android. (TextLayout, Font, Graphics2D, & more)

7 votes

I've been toying around in Android and attempting to port over a Java app. Below are some questions regarding to issues I've run into and would like some guidance on.

It is a rather large question (multiple questions rather). However, I'm not asking them blindly as I have researched what I could about them and attempted to put my understanding to use. I've put time into asking the questions in hopes that they are half-ways clear on what I'm wanting to achieve.

I'll be offering half of my rep as a bounty since I'm hoping for thorough answers and help, hopefully it will be enough to entice a few people to help.

In advance, thank you for your time and help! (looking forward to reading responses).

TextLayout && Font && Graphics2D

In question are the following classes and methods:

  • TextLayout
  • TextLayout.getAdvance()
  • TextLayout.getAscent()
  • TextLayout.draw()
  • Graphics2D.getFontRenderContext()

I'm not quite sure what is equivalent of TextLayout in Android. I had read that some make a TextView and use that, but am unsure if that will

work for the following. I'll provide some source of what I'm wanting to do and perhaps one can help me.

Java Source:

private Font myStringFont = new Font("Helvetica", Font.BOLD, 12);
private String myString = "My Test String";
private int midX = getWidth() / 2;
private int midY = getHeight() / 2;
Graphics2D g2 = new Graphics2d();

TextLayout layout = new TextLayout(myString, font, g2.getFontRenderContext());
g2.drawString(myString, midX - ((int)layout.getAdvance() /2), midY);

Android Replication Attempt:

Canvas canvas;
Paint paint;
private String myString = "My Test String";
private float midX = getWidth() / 2;
private float midY = getHeight() / 2;
//Unsure what to do about TextLayout <- this is where I need an alternative
canvas.drawText(myString, midX - /* whatever my alternative to layout.getAdvance() is */ /2), midY);

Im stuck at determining how to create a TextLayout and what to do for the method getAdvance(). I noticed that in Paint.FontMetrics() there are

some possible alternatives, but I don't know if any compare.

I'm also unsure how to deal with the following Java code:

Graphics2D g2 = new Graphics2d();
private int midX = getWidth() / 2;
private int midY = getHeight() / 2;

TextLayout layout = new TextLayout(myString, g2.getFont(), g2.getFontRenderContext());
layout.draw(g2, midX, MidY);

Review/Summary of Questions Above:

  • What is an Android alternative for TextLayout?
  • What is equivalent to TextLayout.getAdvance()? (Am I able to use fontMetrics to achieve it?)
  • Are there Android equivalents to Graphics2D.getFontRenderContext()?
  • Can you provide example source for Android?

This is currently one of my biggest issues with porting Java over to Android. I would be greatful for any help, advice, examples, etc.

Font

Below are the methods I am wanting to replicate that deal with font, textlayout, and graphics2d. The first source is the Java methods and

below it is my attempt to replicate it.

In question are the following classes and methods:

  • Font.deriveFont(float size) Creates a new font objects by replicating the current font object and applying a new style to it
  • TextLayout.getAdvance() The advance is the distance from the origin to the advance of the rightmost (bottommost) character measuring in the line direction
  • Graphics2D.setRenderingHint(RenderingHints, RenderingHints)
  • Graphics2D.getFontRenderContext() Encapsulates application hints such as anti-aliasing and fractional metrics

Java Source:

private String myString = "Print this test statement";
private int myStringFontSize = 15;
private Color myStringFontColor = Color.red;
private Font myStringFont = new Font("Helvetica", Font.BOLD, myStringFontSize);
private int midX = getWidth() / 2;
private int midY = getHeight() / 2;

public drawString(Graphics2D g2) {
    g2.setFont(myStringFont.deriveFont(determineFontSize(g2, myString)));
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALISING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    TextLayout layout = new TextLayout(myString, g2.getFont(), g2.getFontRenderContext());

    g2.setPaint(myStringFontColor);
    g2.drawString(myString, midX - ((int) layout.getAdvance() / 2), midY);
}

protected float determinFontSize(Graphics2D g2, String myString) {
    int space = getWidth();
    float fontSize = 1.0f;
    float finalFontSize = fontSize;

    while(fontSize < 25) {
        Font font myString.deriveFont(fontSize);
        Textlayout layout = new TextLayout(waitingMessage, font, g2.getFontRenderContext());

        if(layout.getAdvance() > space) {
            finalFontSize = fontSize - 2;
            break;
        }
        fontSize++;
    }
    finalFontSize = fontSize - 4;
    return finalFontSize;
}

Android Attempt:

private String myString = "Print this test statement";
private int myStringFontSize = 15;
private int myStringFontColor = Color.RED;  //Android uses int rather than Color
Typeface tf = new Typeface();               //Android uses Typeface rather than Font  
private float midX = getWidth() / 2;        //Changed to float because drawText requires float
private float midY = getHeight() / 2;       //changed to float because drawText requires float


public drawString(Canvas canvas, Paint paint) {
    tf.create("Helvetica", BOLD);
    paint.setTypeface(tf);
    paint.setTextSize((float) myStringFontSize);

    paint.setTextSize(determineFontSize(canvas, myString, paint);
    paint.setAntiAlias(true);
    //NOT SURE WHAT TO DO WITH TextLayout YET

    paint.setColor(myStringFontColor);
    canvas.drawText(myString, midX - ((int)layout.getAdvance() / 2), midY, paint);  //Not sure how to deal with layout.getAdvance() just yet    

}

protected float determineFontSize(Canvas canvas, String myString, Paint paint) {
    float fontSize = 1.0f;
    float finalFontSize = fontSize;
    int space = getWidth();

    while(fontSize < 25) {
        paint.setTextSize(fontSize);
        //NOT SURE WHAT TO DO ABOUT TextLayout.getAdvance() YET or g2.getFontRenderContext()

        if(layout.getAdvance() > space) {
            finalFontSize = fontSize - 2;
            break;
        }
        fontSize++;
    }
    finalFontSize = fontSize - 4;
    return finalFontSize;            
}

Final Questions About The Above Methods:

  • What alternative do I have for TextLayout.getAdvance()? (Ignore if it has been answered due to the question regarding TextLayout)
  • What alternative do I have for Graphics2D.getFontRenderContext()?
  • Does my Android source replicate the Java source? If not, what needs to be changed?
  • Are there better ways of doing this? If so, how?

Elipse2D.Double(double x, double y, double w, double h)

Is there a way to make a subclass of oval to create something equal to Java Ellipse2D.Double? If so, how would one go about it?

ComponentAdapter && ComponentEvent

I have these in java because my component is able to be resized, in Android what are the equivalents of these for views? (if any)

The TextLayout, Font and Graphics2D question can be achieved simply in Android by using a TextView, some layout attributes in the layout xml file and possibly augmenting it with some code. To illustrate with an example, the TextView could be declared in the layout xml as follows:

<TextView android:id="@+id/logo"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:paddingTop="5dip"
    android:text="Fancy Logo"
    android:textSize="24sp"
    android:layout_weight="0.8"
    android:textStyle="bold"
    android:textColor="@color/black" />

Most of the attributes are self-explanatory, but the layout_width hasn't been set as we'll augment the TextView with a Font which will affect the width it takes up.

AssetManager assetManager = getContext().getAssets();       

    Typeface tf = Typeface.createFromAsset(assetManager,"GILB.TTF");                

    TextView logo = (TextView)findViewById(R.id.logo);
    logo.setTypeface(tf);

The setTypeface() method is overloaded with an additional style parameter which can also provide bold and/or italic effects.

The specific position this text is drawn on-screen will be dependent on the layout or combinations of layouts you choose e.g. RelativeLayout, AbsoluteLayout, etc - there are a lot of resources which can teach you how to use these to good effect.

If this is too limited, then you can draw on the Canvas directly. Here, you can specify a Paint, or TextPaint object, where you can set anti-aliasing and several other paint effects.

In place of Ellipse2D.Double, you could use Canvas.drawOval(RectF oval, Paint paint) where the RectF object specifies the bounding box for the oval.

To enable views (components) to be resized automatically, you should use where possible, flexible layout attributes such as wrap_content, match_parent or fill_parent rather than specific 'dip' sizes. Graphics should be converted to 9-patch formats so that they can stretch to accommodate size changes.

If you really need to calculate the length of text, or specify text size to fit a specific physical space, then you can refer to this answer on SO.

Hope this helps answer your questions.

Query Android's SQLiteDatabase using Regex

3 votes

I am trying to fetch entries from a SQLiteDatabase in an Android program using the query function using the selection parameter. I have had success with simple pattern matching using the SQLite's LIKE and the % wildcard. Now I want to do more complex pattern matching using regular expressions.

According to the SQLite website, for the REGEXP operator to function, it must be user defined. Has anyone had any success creating use defined SQLite functions for Android's SQLiteDatabase? Or has anyone found another way to use regular expressions when searching through strings in a database?

As described here

The REGEXP operator is a special syntax for the regexp() user function. No regexp() user function is defined by default and so use of the REGEXP operator will normally result in an error message. If a application-defined SQL function named "regexp" is added at run-time, that function will be called in order to implement the REGEXP operator.

But there is GLOB which is little more advanced than LIKE.

How to turn on bluetooth on button click

2 votes

In my application, I need to turn on bluetooth of my device on a button click. How can I achieve that? An example will be really helpful. Also, what permissions I require to include in my mainfest.xml for the same?

Following are code excerpts from android documentation on Bluetooth

In the manifest file for permissions:

<manifest ... >
  <uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>

Source code to enable Bluetooth

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth
}

if (!mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

If enabling Bluetooth succeeds, your Activity will receive the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded "No") then the result code will be RESULT_CANCELED.

I want to populate Phone contacts to spinner

2 votes

I want to populate contact names from phone into spinner widget. How to call that without moving to another intent. As I don't have that much knowledge in this.

Spinner needs an adapter, you can look at this code for getting the adapter.

This code helps in loading the spinner.

Will a Handler defined in an Activity leak in this scenario...

2 votes

I've got an activity with a handler defined:

final Handler updateHandler = new Handler() {
    public void handleMessage(Message msg) {
       // Do stuff.
    }
};

In my onCreate method, if I assign this handler to a static list outside of my Activity, will it leak (or rather, will that outside list keep a reference to my activity forever)? I.e,:

@Override
public void onCreate(Bundle savedInstanceState) {          
      SomeStaticClass.addHandler(updateHandler);
}

...

public class SomeStaticClass {
    static List<Handler> handlers = new ArrayList<Handler>();

    public static void addHandler(Handler handler) {
         handlers.add(handler);
    }
}

In my onCreate method, if I assign this handler to a static list outside of my Activity, will it leak (or rather, will that outside list keep a reference to my activity forever)?

Yes. Do not put Handlers in static data members.