Friday, February 26, 2010

Http client API Post method implementation:

Android client side
1.create simple activity with edit text.
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);       
        httpHelper = new HttpHelper();
        etContents =(EditText) findViewById(R.id.etContents);
    }


2.Create Name Value Pair add parameters user name and  password. 

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("userName", "nava"));
            nameValuePairs.add(new BasicNameValuePair("password", "nav"));
            HttpResponse response = httpHelper.doPost("URLHERE", nameValuePairs);
           

           
3.Create http post method and set header and entity. Create Default Http Client,Http Context and execute the  http request.

DefaultHttpClient httpClient;
HttpContext localContext;
HttpPost request = new HttpPost(url);
        HttpResponse response = null;   
        Log.d("Service Call ",url);
        try {
            // Set parameters
            if (parameters != null) {
                request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                request.setEntity(new UrlEncodedFormEntity(parameters));
            }           
            response = httpClient.execute(request, localContext);
           
           
        } catch (ClientProtocolException e) {
            // put your code here
        } catch (IOException e) {
            // put your code here
        }

4.Get the response from the server and display the content to edit text

try {               
                InputStream instream = response.getEntity().getContent();
                content = httpHelper.inconvertibility(instream);
                etContents.setText(content);
            } catch (IllegalStateException e1) {               
                e1.printStackTrace();
            } catch (IOException e1) {               
                e1.printStackTrace();
            }


Server side implementation:

1.create simple web application and that application receive the request parameter.

 public void crmLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userName = "";
        String password = "";

        String result = "";

      
        if (request.getParameter("userName") != null) {
            userName = request.getParameter("userName");
        }

        if (request.getParameter("password") != null) {
            password = request.getParameter("password");
        }

2.get the user name and password from the request and set the user name and password to response.

result="userNamee="+userName+""+"password="+password;

        response.setContentType("text/plain");
        response.setHeader("Cache-Control", "no-cache");
        try {
            response.getWriter().write(result);
        } catch (Exception e) {
        }


Sample SAXParser in Android

In this aritcle discuss about  “How to properly parse XML  using a SAXParser”. 

1.Create  a Customized Handler based on the XML
2.Create a ParserHelper Class
3.Implement the parser and get the Data.

Create  a Customized Handler based on the XML
You can create customized handler using the DefaultHandler class for your xml.

Step : 1 [Create a Handler which extends DefaultHandler]
    class MyDefaultHandler extends DefaultHandler {
    }
   



Step : 2 [ Override the Methods and implement the Code]       
   
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        _tmpValue = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equalsIgnoreCase("uname")) {
            _tmpKey = _tmpValue;
        } else if (localName.equalsIgnoreCase("pwd")) {
            userList.put(_tmpKey.trim(), _tmpValue);
        }
    }


Create a ParserHelper Class
Create an instance for customized handler class
    MyDefaultHandler df = new MyDefaultHandler();   

Create an instance for SAXParserFactory,SAXParser and XMLReader
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();


Set the content Handler
    xr.setContentHandler(df);

Set the XML Content   
Type 1:
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(parseContent));


Type 2:
    URL url = new     URL("http://www.DOMAON.com/File.xmll");
   
   
Parser the XML
    xr.parse(is); [For type1]
    xr.parse(new InputSource(url.openStream())); [For type2]


Implement the parser and get the Data

Create an instance for helper class and call the parserContent method
  
    SAXHelper sh = new SAXHelper();
    sh.parseContent(content);
             

Sample Source

MyDefaultHandler.java


class MyDefaultHandler extends DefaultHandler {

    String _tmpValue = "", _tmpKey = "";
    public HashMap<String, String> userList = new HashMap<String, String>();

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        _tmpValue = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equalsIgnoreCase("uname")) {
            _tmpKey = _tmpValue;
        } else if (localName.equalsIgnoreCase("pwd")) {
            userList.put(_tmpKey.trim(), _tmpValue);
        }
    }
}


SAXHelper.java
public class SAXHelper {   
    public HashMap<String, String> userList = new HashMap<String, String>();
    public void parseContent(String parseContent) {
        MyDefaultHandler df = new MyDefaultHandler();
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();           
            xr.setContentHandler(df);
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(parseContent));           
            xr.parse(is);           
            userList = df.userList;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Implementation Class

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        String content = "<root><uname>ganesan</uname><pwd>pwd2</pwd> <uname>rama</uname><pwd>pwd1</pwd> </root>";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.TextView01);
        SAXHelper sh = new SAXHelper();
        sh.parseContent(content);
        String data = (String) sh.userList.get("ganesan");
        Log.d("DATA", data);
        tv.setText(data);

    }
  


Wednesday, February 24, 2010

Android Apps - What I Use

I've been asked by a few people for recommendations of Android applications that I use.  I've made a few lists, but this one is the most comprehensive of those lists.  Most links below go to Androlib which have QR codes for you to scan with your phone.
  • Advanced Task Manager (free) - Great for killing hanging processes and keeping yourself from needing to reset the phone.
  • Astro File Manager (free) - because everyone needs a file manager
  • BookmarkBR (free) - Backup utility for your browser bookmarks.
  • CalWidget (free) - Quick at a glance widget for home screen.
  • Documents To Go Full ($29.99 $14.99 for a limited time) - Kinda spendy, but great if you need to open/edit docs or spreadsheets or view pdfs on your phone.  I've done a few homework assignments in a pinch with this, very handy to have.
  • Draw! (free) - Great drawing app to entertain kids with.
  • Foursquare (free) - Great app for checking in and letting the world know where you are, much, much better than their mobile website.  You can view offers and other foursquare specific things within the app.
  • FxCamera (free) - My wife loves this because she can make "polaroid" pictures with it.
  • GDocs (free) - Great if you need offline access to your google docs. Allows editing of Google Docs and quick access to Google Spreadsheets.
  • Google Voice (free) - Great app for checking your Google Voice messages.  Its also great that it can take over your phone and make calls as your Google Voice number.
  • GPS Status (free) - Get better information from the GPS radio, compass included.
  • Live Bookmarks (free) - A great desktop widget for quick access to all of your browser bookmarks.
  • Reveal Reader (free) - A simple scripture reader for for those interested in the LDS Standard Works, and other church-related publications including hymns.  Support for bookmarking and in-app downloads, so you don't have to go hunting for the files yourself.
  • Ringdroid (free) - customize mp3 on your phone and make them into ringtones 
  • Seesmic (free) - Great for twittering, nice big compose screen, integration with the share menu and it doesn't have a huge footprint.  Twitter updates come in pretty reliably, yfrog/twitpic/etc image preview saves time.
  • Shazam (free) - Good for identifying songs on the radio or elsewhere.
  • Skydeck (free) - Great if you want to keep a backup of your messages and calls on the web, check out their check out their site.  Their app also has a caller id function that identifies calls from people not in your contacts.
  • TextEdit (free) - Small little application lets you jot down notes, w/o internet access.
  • Voice Recorder (free) - Record audio and email it.
  • Yelp (free) - Great for finding a place to eat.

Other apps that I've had installed but deleted due to space limitations on the G1: Google Sky Map, Twidroid Pro, Google Goggles, Layar, Evernote, Brightkite, Steel, Locale, Pandora, and Last.fm.  Most were great, but I didn't use them often enough to warrant using the space to keep them.

Let me know in the comments if there are some alternate apps that I should take a look at.

Tuesday, February 23, 2010

Steps to create a Sample TextToSpeech

The following steps to help you create a Sample TextToSpeech(TTS) Application

1. Create a MainActivity which is extends Activity and Implements OnInitListener interface
2. Check the Text Speech Feature using the " TextToSpeech.Engine.ACTION_CHECK_TTS_DATA " or Install the Feature. Ensure your API 1.6 or greater than the 1.6
Because starting with Android 1.6 (API Level 4), the Android platform includes a new Text-to-Speech (TTS) capability. Also known as "speech synthesis", TTS enables your Android device to "speak" text of different languages.
3. Create TextToSpeech instance or installed the TextToSpeech API and create instance.
4. Configure with locale Implementation
5. Call the speak() to test the TTS


Create a MainActivity which is extends Activity and Implements OnInitListener interface
public class MainActivity extends Activity implements OnInitListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        }
        @Override
    public void onInit(int status) {
    }
}




2. Check the Text Speech Feature using the " TextToSpeech.Engine.ACTION_CHECK_TTS_DATA " or Install the Feature. Ensure your API 1.6 or greater than the 1.6
Because starting with Android 1.6 (API Level 4), the Android platform includes a new Text-to-Speech (TTS) capability. Also known as "speech synthesis", TTS enables your Android device to "speak" text of different languages.
    Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

3. Create TextToSpeech instance or installed the TextToSpeech API and create instance.
private TextToSpeech mTts;
    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) {
        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // success, create the TTS instance
                mTts = new TextToSpeech(this, this);
            } else {
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(
                    TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }


4. Configure with locale Implementation
    @Override
    public void onInit(int status) {
        mTts.setLanguage(Locale.US);   
    }


5. Call the speak() to test the TTS
    mTts.speak("hai this is for testing, Karhtik is testing this application", TextToSpeech.QUEUE_FLUSH, null);

6. Sample Code
public class MainActivity extends Activity implements OnInitListener {
    int MY_DATA_CHECK_CODE = 1;
    private TextToSpeech mTts;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
    }
   

    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) {
        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // success, create the TTS instance
                mTts = new TextToSpeech(this, this);
            } else {
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(
                    TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }

    @Override
    public void onInit(int status) {
        mTts.setLanguage(Locale.US);
        mTts.speak("hai this is for testing, Karhtik is testing this application", TextToSpeech.QUEUE_FLUSH, null);
    }
}


Hope this is helpful for you.

Android Remote Service Sample

The following article used to create a remote service
1.Create a Project Called RSDemo.


2.Create a aidl in your IDE
:
AIDL (Android Interface Definition Language) is an IDL
language used to generate code that enables two processes on an Android-powered device
to talk using interprocess communication (IPC). If you have code
in one process (for example, in an Activity) that needs to call methods on an
object in another process (for example, a Service), you would use AIDL to
generate code to marshall the parameters.







AIDL is a simple syntax that lets you declare an interface with one or more methods, that can take parameters and return values. These parameters and return values can be of any type, even other AIDL-generated interfaces. However, it is important to note that you must import all non-built-in types, even if they are defined in the same package as your interface.

Sample AIDL File
package <<<YOUR PROJECT  PACKAGE >>>;
interface IMyService {
            int getStatus();
 }


3. Ensure the Stub file in gen Folder.

4. Create Service and create an instance for the stub class


  1. Create a Service Class

  2. Create a instance for stub class with implmentation

  3. Return the instance while calling the IBind Method.


public class MyRemoteCounterService extends Service {

/**

* @see android.app.Service#onBind(Intent)

*/


private IMyService.Stub imyserviceStub = new IMyService.Stub() {

@Override

public int getStatus() throws RemoteException {

return 1;

}

};


@Override

public IBinder onBind(Intent intent) {

Log.d("REMOTE SERVICE ", "INVOKED");

return imyserviceStub;

}


@Override

public void onCreate() {

super.onCreate();

}


@Override

public void onStart(Intent intent, int startId) {

super.onStart(intent, startId);

}


@Override

public void onDestroy() {

super.onDestroy();

}

}


5. Create a Client Class Access the Service.


1.Create instances for Button for invoking and release the Connection
2. Create a class Service Connector using the ServiceConnector Interface.
3. Create a Instance for SeviceConnector and Stub class
4. Bind the service using the bindService()
5. Invoke the Service

Create a class Service Connector using the ServiceConnector Interface

class MyServiceStatus implements ServiceConnection {

@Override

public void onServiceConnected(ComponentName arg0,

IBinder arg1) {

iMyService = IMyService.Stub.asInterface((IBinder)arg1);

Log.d("@G RemoteService","Connected");

}

@Override

public void onServiceDisconnected(ComponentName name) {

iMyService = null;

Log.d("@G RemoteService","DisConnected");

}

}


Create a Instance for SeviceConnector and Stub class

ivate IMyService iMyService;

private MyServiceStatus conn;


Bind the service using the bindService()

if (conn == null) {

conn = new MyServiceStatus();

Intent i = new Intent();

i.setClassName("com.rsdemo", "com.rsdemo.MyRemoteCounterService");

bindService(i, conn, Context.BIND_AUTO_CREATE);

}


Invoke the Service

try {

counter = iMyService.getStatus();

} catch (RemoteException re) {

Log.e(getClass().getSimpleName(), "RemoteException");

}



6. Sample Source

1. AIDL Implementation - IMyService.aidl

package com.rsdemo;


interface IMyService {

int getStatus();

}




  1. Service - MyRemoteCounterService

public class MyRemoteCounterService extends Service {

/**

* @see android.app.Service#onBind(Intent)

*/


private IMyService.Stub imyserviceStub = new IMyService.Stub() {

@Override

public int getStatus() throws RemoteException {

return 1;

}

};


@Override

public IBinder onBind(Intent intent) {

Log.d("REMOTE SERVICE ", "INVOKED");

return imyserviceStub;

}


@Override

public void onCreate() {

super.onCreate();

}


@Override

public void onStart(Intent intent, int startId) {

super.onStart(intent, startId);

}


@Override

public void onDestroy() {

super.onDestroy();

}

}


  1. Client

/** Called when the activity is first created. */

private IMyService iMyService;

private MyServiceStatus conn;

int counter = 0;


@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);


Button invoke = (Button) findViewById(R.id.Button01);

Button release = (Button) findViewById(R.id.Button02);


if (conn == null) {

conn = new MyServiceStatus();

Intent i = new Intent();

i.setClassName("com.rsdemo", "com.rsdemo.MyRemoteCounterService");

bindService(i, conn, Context.BIND_AUTO_CREATE);

}


release.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

unbindService(conn);

conn = null;

}

});


invoke.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

if (conn == null) {

Toast.makeText(MainActivity.this,

"Cannot invoke - service not bound",

Toast.LENGTH_SHORT).show();

} else {

try {

counter = iMyService.getStatus();

} catch (RemoteException re) {

Log.e(getClass().getSimpleName(), "RemoteException");

}

}

Toast.makeText(MainActivity.this, counter + "",

Toast.LENGTH_LONG).show();

}

});


}


class MyServiceStatus implements ServiceConnection {


@Override

public void onServiceConnected(ComponentName arg0, IBinder arg1) {


iMyService = IMyService.Stub.asInterface((IBinder)arg1);

Log.d("@G RemoteService","Connected");

}


@Override

public void onServiceDisconnected(ComponentName name) {

iMyService = null;

Log.d("@G RemoteService","DisConnected");

}


}



4. Layout - main.xml

<?xml version="1.0" encoding="utf-8"?>

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

android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent">

<TextView android:layout_width="fill_parent"

android:layout_height="wrap_content" android:text="@string/hello" />

<Button android:id="@+id/Button01" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="Invoke"></Button>

<Button android:id="@+id/Button02" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="Release"></Button>

</LinearLayout>








Monday, February 22, 2010

My First Chrome Extension - My Shortcuts


I threw together a Chrome extension a while back when extensions were only in the development build of Chrome.  Since then I've changed my extension quite a bit, and it now has around 4,000 weekly users.  

When I first put the extension together, it was a toolstrip on the bottom of the Chrome window.  These have since been removed in favor of BrowserActions, which are single buttons on the Chrome UI.


v. 1.0 - 1.2

I thought the toolstrip worked pretty well, but you can see how my extension would get out of hand with more than a few links.  I made the switch to using the BrowserActions, this was relatively simple, I just changed the layout to vertical.

v. 1.3

I've been making incremental changes over the last few week or so, to both speed it up and add features.  The most recent release v.2.0.3 includes a new feature that allows users to create their own links to go along with the included Google links.

v 2.1


The entire project was written with InType, which is an awesome Notepad replacement with tabs and syntax highlighting.  It works very well for javascript/css/html editing, though debugging must be done within Chrome.  Highly recommend this as a replacement for a quick text editor.


In making these changes I've tried to optimize the extension to make it as small and fast as possible.  I used Google Closure tools to minify the javascript with their Closure Compiler.  In order to do this I pulled all of my js code out of the popup and options pages and put them in their own script files.  The minification of my js files saved me a few kilobytes of space.


I was able to compress the stylesheet using CSSDrive's CSS Compressor, which only saved a few bytes, but helps nonetheless.


I ran all of my images through PunyPNG, which shrunk the overall image footprint, even though only half of my images saw any change.


I'll continue making changes and listening to the feedback from users and hopefully keep it current and usable.  Thanks for the support.


Get it here: http://bit.ly/MyShortcutsChrome