Archive for the ‘java’ Category

quicktip: Working with strings.xml in Android and little bit about @

Saturday, February 20th, 2010

Very simple so straight to the point.

BAD:

In your xmls
- <Button android:id="@+id/buy_button" android:text="Buy Me" />

In your java code
- myButton.setText("Second Button");

GOOD:

Define your strings in strings.xml (You can name it anything) and place it in ‘res/values’ folder


<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="buy_button">Buy</string>
</resources>

and then


- <Button android:id="@+id/buy_button" android:text="@string/buy_button” />
- myButton.setText(this.getString(R.string.buy_button));

Syntax for using a ‘resource’ in a xml or code is :
package.R.resource_type.resource_name
and
@[package:]resource_type/resource_name

NOTE: package here does not mean ‘java package’ but package == application, so if you are accessing a resource which is defined in your own app you can skip it. Thats why we use @strings/name or directly R.strings.name. Similarly to use resources defined by android we will use @android:string/name or android.R.string.name

For converting R.string.id to String you can either use getString(int) or getString(int, Object…) for adding dynamic values.

quicktip: How to convert a view to an image (android)

Wednesday, February 10th, 2010

This is a quick tip to convert or draw your view on a canvas so that you can either show it as preview or use it for any drag - drop kind of operation. Very simple and self explanatory so just posting the code


View viewToBeConverted;

Bitmap viewBitmap = Bitmap.createBitmap(viewToBeConverted.getWidth(), viewToBeConverted.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(viewBitmap);

viewToBeConverted.draw(canvas);

Thats it, now you can use ‘viewBitmap’ as a normal image. You can change a few parameters to create different kinds of image, for eg when you drag your app icon on bring it on the trash can to drop it becomes red etc

Android Push Notification

Tuesday, December 1st, 2009

Push Notification:

Push Notification allows an application to listen for messages being ‘pushed’ to it from the server.
Through Push Notification, our apps can provide uses even when they aren’t running.

Different techniques that could be used for push notifications in android:

1)  Polling:  In this technique device is polling the server on a regular basis to see if there is anything there.

untitled.bmp

Polling that heavily just to check for notification is not a good idea,that would hurt battery life pretty badly after not too long.

2)  Creating a service: In this technique service create a persistent connection to your server.
This will also drain the phone’s battery and it will create problem on server side also if you had more users

3)  SMS: In this method clients gets notified by SMS.

untitled2.bmp

This technique is better as compare to other techniques because:

1) Transfer content as soon as available
2) Save device battery
3) Reduce data traffic for user

Way to implement push via SMS:

1) Your application should add permission in manifest :
Permission:  <uses-permission android:name=”android.permission.RECEIVE_SMS” />
2) and Registers a BroadcastReceiver, either in the manifest XML or in Java, and will get control when the events occur.
<receiver android:name=”.ReceiverClass”>
<intent-filter>
<action android:name=”android.provider.Telephony.SMS_RECEIVED” />
</intent-filter>
</receiver>
3) SMS Header may contain “app port” field that is dedicated range of free usable port numbers.Port handling not yet supported in Android 1.6.
4) You’d have to parse the PDU and get the port from there manually, you can listen to all SMS messages, parse the PDU of each incoming message and see if the destination port
matches the one that you are expecting. But so can other apps.so there’s no way to ensure that just one specific app gets to know about an incoming SMS to a specific port.
5) After matching ports appliaction can handle notification with the help of notification manager.
The problem with this method is that Android currently has no way to cancel the notification that is sent by the messaging app.So for every notification your app gets, the OS will also show a text message.

Android NDK - an introduction (How to work with NDK)

Monday, October 26th, 2009

What is the Android NDK?

The Android NDK is a companion tool used only in conjunction with Android SDK which allows application developers to build performance-critical portions of their apps by use of native (C/C++) code.

This provide benefits in form of reuse of existing code and increased speed.

Contents of NDK:

  • A set of tools and build files for generating native code libraries from C and C++ sources.
  • A way to embed the corresponding native libraries into application package files (.apks) that can be deployed on Android devices.
  • A set of native system headers and libraries supported starting from Android 1.5 .
  • Documentation, samples, and tutorials.

Download NDK from http://developer.android.com/sdk/ndk/1.6_r1/index.html and uncompress it.Now run the script in <NDK>/build/host-setup.sh.This creates <NDK>/out/host/config.mk which configure NDK for system.

How to write an application using NDK?

Follow underneath steps to create our own application using NDK and make it running on emulator.

Write an Android Activity

You need to include following lines of extra code in our java file.

  • Call native method inside on create method.
  • Declare native method outside oncreate method.
  • Call to “System.loadLibrary” method inside a static initializer block to load our shared library object.

package com.example.FileLoaderActivity;

public class FileLoaderActivity extends Activity {

private static String TAG = “FileLoaderActivity”;

// The name of a test file to write

private static String FILENAME = “hello”;

// The full path to the test file

private static String PATH = “/data/data/com.example.FileLoaderActivity/” + FILENAME;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

……………

// Call the native method to read the file just written

byte[] bytes = loadFile(PATH);

…………..

}

public native byte[] loadFile(String fileName); static {

System.loadLibrary(”fileloader”);

}

}

Generating C/C++ header files For generating C/C++ header file for our shared library:

  • Build project which generates Java.class files under <project_home>/bin
  • Use javah tool to generate a C/C++ header file.

Issue the following command at the top of <project_home>, my command looks like:

javah -o fileloader.h -classpath bin com.example.FileLoaderActivity.FileLoaderActivity

The above command will generate a file called fileloader.h .

Creating our Shared Library

Create two folders which will contain source code and make files:

  • mkdir -p ~/workspace/<project_home>/jni folder - contain the source code for our shared library.
  • mkdir -p $NDK_HOME/apps/fileloader folder- “project definition” folder for our shared library

Now copy header file ‘hellondk.h’ from Eclipse project folder to ~/workspace/<project_home>/jni/

For building our NDK project, we need to create two Makefiles which will specify how and from where to pick source code and library file.

  • Android.mk
  • Application.mk

~/workspace/<project_home>/jni/Android.mk

Android.mk file describes source file to build system and its contents are :

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := fileloader

LOCAL_SRC_FILES := fileloader.c

LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog

include $(BUILD_SHARED_LIBRARY)

$NDK_HOME/apps/fileloader/Application.mk

Application.mk file describes modules that are needed by your application and it looks like:

APP_PROJECT_PATH := ~/workspace/FileLoaderActivity

APP_MODULES := fileloader

Creating Shared Library Source

Now create C source file for shared library which defines JNI method called by Java file.Signature of this Jni method should match with fileloader.h file generated by eclipse build system.

~/workspace/FileLoaderActivity/jni/fileloader.c

jbyteArray Java_com_example_FileLoaderActivity_FileLoaderActivity_loadFile

(JNIEnv* env, jobject thiz, jstring filename)

{

……………………..

}

Compiling our Shared Library

Change current working directory to $NDK_HOME and run command “make APP=fileloader”.You can find your shared library into folder $NDK_HOME/out/apps/fileloader/ directory.You can now run our FileLoaderActivity project from within Eclipse. Dont forget to push file “hello” mentioned in java code before running project.Here’s a screenshot of what you should see in the emulator.

device.png

Android 1.6 Gestures

Thursday, October 8th, 2009

Android 1.6 platform introduces entirely new gestures framework that finally lets developers build gestures into their apps using the new GestureBuilder tool included in the SDK. Gestures framework provides application developers with a framework for creating, storing, loading, and recognizing gestures and associating them with specific actions.

Need of Gestures:
Touch screens are a great way to interact with applications on mobile devices. With a touch screen, users can easily tap, drag, fling, or slide to quickly perform actions in their favorite applications. But it’s not always that easy for developers. With Android, it’s easy to recognize simple actions, like a swipe, but it’s much more difficult to handle complicated gestures, which also require developers to write a lot of code. In such a situation we can use gestures.This API, located in the new package android.gesture.

We decided to try it out and see how it works. For sample we made a list and used the ‘drag to dustbin’ gesture to delete individual list items.

Step 1: Creating / defining our own gestures using GestureBuilder

GestureBuilder

Step 2: Copy the gesture file created by GestureBuilder from SD card and put it into ‘res/raw’ folder of your project.

Step 3: Write code to handle the event generated by your gesture

step1.png

step2.png

Android tip #1 ContentProvider , Accessing local file system from WebView / showing image in webview using content://

Saturday, January 10th, 2009

ok, this was a tough one.
First be informed that this is something Google (Android people) are trying to prevent i.e. letting browser (WebView) have access to the local file system. In earlier releases of SDK you could access local files using ‘file://’ but it is stopped now. Then there was an option where you can provide a WebViewClient and implement shouldOverrideUrlLoading to make it work. This was also removed.
The way to make it work now is by implementing your own ContentProvider, there is lot of discussion and documentation on implementing ContentProvider but all that is completely redundant (not needed). The solution is very simple, create your own ContentProvider and only override


public android.os.ParcelFileDescriptor openFile(android.net.Uri uri, java.lang.String mode) throws java.io.FileNotFoundException

Rest of the code in ContentProvder is not needed for this problem.

Step 1:
Declare your Content Provider in AndroidManifest.xml


<provider android:name="MyDataContentProvider"  android:authorities="com.techjini" />

Step 2:
Create your ContentProvider and implement openFile
All you have to do is get real path from uri, open it and return the descriptor


URI uri = URI.create("file:///data/data/com.techjini/files/myImage.jpeg");
File file = new File(uri);
ParcelFileDescriptor parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
return parcel;

Step 3:
(You need this step only if file is not already present on the device/sdcard)
Save your content to the file. Following is an example to store a Bitmap


FileOutputStream fos = openFileOutput("myImage.jpeg", Activity.MODE_WORLD_WRITEABLE);
imageView.getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, fos);

fos.flush();
fos.close();

You can find out where your image is stored using


System.out.println(getFilesDir().getAbsolutePath());

Step 4:
Access the file in WebView


myWebView.loadUrl("content://com.techjini/myImage.jpeg");
//com.techjini is what you mentioned in 'android:authorities' in your AndroidManifest.xml

Looks simple :)

JBoss tip #5 Keeping the project in exploded .war file in some other location other than deploy folder

Thursday, December 25th, 2008

This is how you can increase your productivity while developing an app on Jboss, no need to package and deploy again and again, reduced development and testing time.

Open %JBOS_HOME%\server\default\conf\jboss-service.xml and add the new location


    <attribute name="URLs">
        deploy/, E:/ file:/var/opt/apps/
     </attribute>

JBoss tip #4 Increasing the jta time out from default 5 mins to more

Wednesday, December 24th, 2008

Open %JBOSS-HOME%\server\default\conf\jboss-service.xml
[sourcecode language=’xml’]

name="jboss:service=TransactionManager">
3600
${jboss.server.data.dir}/tx-object-store

[/sourcecode language=’css’]
[sourcecode language=’xml’]
3600
[/sourcecode language=’css’] by default it would be 300, here we changed it to 3600 which is 1 hr.

JBoss tip #3 Accessing the application out side the local machine

Sunday, December 21st, 2008

Open %JBOSS_HOME%\server\default\deploy\jboss-web.deployer\server.xml and change the address to “0.0.0.0″


     <Connector port="8081" address="0.0.0.0" maxThreads="250" maxHttpHeaderSize="8192"
        emptySessionPath="true" protocol="HTTP/1.1"
        enableLookups="false" redirectPort="8443" acceptCount="100"
        connectionTimeout="20000" disableUploadTimeout="true" />

Jboss tip #2 Changing the default port number 8080 to some other port

Saturday, December 20th, 2008

Open %JBOSS_HOME%\server\default\deploy\jboss-web.deployer\server.xml and change the port as per your requirement.


<Connector port="8081" address="0.0.0.0" maxThreads="250" maxHttpHeaderSize="8192"
        emptySessionPath="true" protocol="HTTP/1.1"
        enableLookups="false" redirectPort="8443" acceptCount="100"
        connectionTimeout="20000" disableUploadTimeout="true" />