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);

    }
  


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>








Wednesday, February 17, 2010

Map Implementation

1. Open Command Prompt and generate using eh keytool


You can the debug.keystore path

> Open Eclipse-> Windows>Preferences>Android>Build



Run the Following command with keystore

> keytool -list -keystore <debug.keystore path>



  1. Register the Certificate fingerprint and get the map view along with api key


Go To http://code.google.com/android/maps-api-signup.html and place your certification key



Register your certification along with your google account.

You can get the Following Data

Thank you for signing up for an Android Maps API key!

Your key is:

<< COPY THE API KEY>>

This key is good for all apps signed with your certificate whose fingerprint is:


CERTIFICATION FINGER PRINTS

Here is an example xml layout to get you started on your way to mapping glory:


<com.google.android.maps.MapView android:layout_width="fill_parent" android:layout_height="fill_parent" android:apiKey="||API KEY||"/>




3. Create a map based android project.


1. Eclipse > New Project > Android Project > Select Google Map 1.5




4. Place MapView in the layout


  1. Create a class extends the MapActivity class

public class MainActivity extends MapActivity {

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

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}


@Override

protected boolean isRouteDisplayed() {

// TODO Auto-generated method stub

return false;

}

}



  1. Create a GeoPoint, MapView and MapController instance.


double latitude = 10.47, longitude = 79.10;

GeoPoint geoPoint = new GeoPoint((int) (latitude * 1000000),

(int) (longitude * 1000000));


MapView myMapView = (MapView) findViewById(R.id.myGMap);

myMapView.setSatellite(false);

myMapView.setBuiltInZoomControls(true);

myMapView.displayZoomControls(true);


MapController myMC = = myMapView.getController();

myMC.setCenter(geoPoint);

myMC.setZoom(15);



Need to Add the User Permission


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


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


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



Need to Add the lib


<application android:icon="@drawable/icon" android:label="@string/app_name">

<uses-library android:name="com.google.android.maps" />

.......

</application>


Hope this is helpful for you