Thursday, December 30, 2010

Call SOAP webservices without using any SOAP Libraries in ANDROID

AIM : Accessing SOAP wsdl methods without including any third party SOAP libraries (like KSOAP2)
SOLUTION:
The below method will call the SOAP server with soap message and returns the ByteArray of response.
private byte[] callSOAPServer() {

        byte[] result = null;
       
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 15000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 35000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
       
        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

        /*
         * httpclient.getCredentialsProvider().setCredentials( new
         * AuthScope("os.icloud.com", 80, null, "Digest"), new
         * UsernamePasswordCredentials(username, password));
         */
        HttpPost httppost = new HttpPost(SERVER_URL );
        httppost.setHeader("soapaction", SOAP_ACTION);
        httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
   
        System.out.println("executing request" + httppost.getRequestLine());
//now create a soap request message as follows:
        final StringBuffer soap = new StringBuffer();
        soap.append("\n");
        soap.append("");
// this is a sample data..you have create your own required data  BEGIN
        soap.append(" \n");
        soap.append(" \n");
        soap.append("" + body);
        soap.append("
\n");
        soap.append("
\n");

        /* soap.append(body); */
// END of MEssage Body
        soap.append("");
        Log.i("SOAP Request", ""+soap.toString());
// END of full SOAP request  message
        try {
            HttpEntity entity = new StringEntity(soap.toString(),HTTP.UTF_8);
            httppost.setEntity(entity); 
            HttpResponse response = httpclient.execute(httppost);// calling server
            HttpEntity r_entity = response.getEntity();  //get response
            Log.i("Reponse Header", "Begin...");          // response headers
            Log.i("Reponse Header", "StatusLine:"+response.getStatusLine());
            Header[] headers = response.getAllHeaders();
            for(Header h:headers){
                Log.i("Reponse Header",h.getName() + ": " + h.getValue());
            }
            Log.i("Reponse Header", "END...");
            if (r_entity != null) {       
                result = new byte[(int) r_entity.getContentLength()];  // read the output message
                if (r_entity.isStreaming()) {
                    DataInputStream is = new DataInputStream(
                            r_entity.getContent());
                    is.readFully(result);
                }
            }
        } catch (Exception E) {
            Log.i("Exception While Connecting", ""+E.getMessage());
            E.printStackTrace();
        }
       
        httpclient.getConnectionManager().shutdown(); //shut down the connection
        return result;
    }

2)You have to parse the output of above function returned byteArray.
for example .,
byte[] initReqrepsonse = callSOAPServer(soapBodymessage );
 ByteArrayInputStream bais=new ByteArrayInputStream(initReqrepsonse);
// now parse the xml
as
    /** Handling XML */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
       
            /** Create handler to handle XML Tags ( extends DefaultHandler ) */
          // ResponseParser  is XML parser class which will parse the XML output.
            ResponseParser myXMLHandler = new ResponseParser();
            xr.setContentHandler(myXMLHandler);
            Log.i("XML data", bais.toString());
            xr.parse(new InputSource(bais));

By this way,you can access Any SOAP webservice methods without using any libraries.
please let me know if any corrections required.

Tuesday, December 14, 2010

Optimize your layouts in ANDROID


Writing user interface layouts for Android applications is easy, but it can sometimes be difficult to optimize them. Most often, heavy modifications made to existing XML layouts, like shuffling views around or changing the type of a container, lead to inefficiencies that go unnoticed.
Starting with the SDK Tools Revision 3 you can use a tool called layoutopt to automatically detect common problems. This tool is currently only available from the command line and its use is very simple - just open a terminal and launch the layoutopt command with a list of directories or XML files to analyze:

$ layoutopt samples/
samples/compound.xml   
7:23 The root-level <FrameLayout/> can be replaced with <merge/>
11:21 This LinearLayout layout or its FrameLayout parent is useless samples/simple.xml
  7:7 The root-level <FrameLayout/> can be replaced with <merge/>
samples/too_deep.xml  -1:-1 This layout has too many nested layouts: 13 levels, it should have <= 10!
  20:81 This LinearLayout layout or its LinearLayout parent is useless
  24:79 This LinearLayout layout or its LinearLayout parent is useless
  28:77 This LinearLayout layout or its LinearLayout parent is useless
  32:75 This LinearLayout layout or its LinearLayout parent is useless
  36:73 This LinearLayout layout or its LinearLayout parent is useless
  40:71 This LinearLayout layout or its LinearLayout parent is useless
  44:69 This LinearLayout layout or its LinearLayout parent is useless
  48:67 This LinearLayout layout or its LinearLayout parent is useless
  52:65 This LinearLayout layout or its LinearLayout parent is useless
  56:63 This LinearLayout layout or its LinearLayout parent is useless
samples/too_many.xml  7:413 The root-level <FrameLayout/> can be replaced with <merge/>
  -1:-1 This layout has too many views: 81 views, it should have <= 80! samples/useless.xml
  7:19 The root-level <FrameLayout/> can be replaced with <merge/>
  11:17 This LinearLayout layout or its FrameLayout parent is useless
For each analyzed file, the tool will indicate the line numbers of each tag that could potentially be optimized. In some cases, layoutopt will also offer a possible solution.
The current version of layoutopt contains a dozen rules used to analyze your layout files and future versions will contain more. Future plans for this tool also include the ability to create and use your own analysis rules, to automatically modify the layouts with optimized XML, and to use it from within Eclipse and/or a standalone user interface.

Windows users: to start layoutopt, open the file called layoutopt.bat in the tools directory of the SDK and on the last line, replace %jarpath% with -jar %jarpath%.
 source: developer.android.com

Mobile Number Portability: Things to Know Mobile Number Portability: Things to Know


November 1, 2010 is the day when mobile number portability (MNP) will be implemented in India, but there are several things about MNP that are not known to the public. Let us take a look at what it is all about.

What is MNP all about?

MNP is the facility that lets a mobile phone subscriber retain his/her original mobile number even after moving from one service provider to another. This is implemented in two different ways around the world. Some countries have the subscriber wanting to port his/her number to contact the new provider, also called the Recipient first. The Recipient then has to work with the old provider known as the Donor to arrange for the smooth transfer of the number. This method is known as Recipient-led porting.

Another, though a less popular way, is to have the subscriber to contact the Donor to obtain a Porting Authorization Code (PAC), which he/she has to provide to the Recipient. The Recipient then has to contact the Donor to complete the porting process. This is known as Donor-led method, but is not popular because there is a chance that the Donor may lure a subscriber to retain his subscription, leading to distortion of competition.

In India, MNP has been elusive so far. It has been implemented the world over and we are one of the last countries left to implement MNP - even our neighbor Pakistan implemented MNP way back in March 2007.

But the Telecom Regulatory Authority of India (TRAI) has made clear that there won't be any further delays and it will surely be implemented on November 1, 2010. To use MNP facility, the subscriber will have to pay a non-refundable fixed charge of Rs.19, while the dipping charge is left to mutual negotiation between the telecom service providers and the MNP service providers. The porting charge shall not exceed the per port transaction charge of Rs.19, according to TRAI directive.

In India, the Recipient-led porting procedure will be used. The porting process would involve a break in service when a number is detached from the donor and added to the recipient, which should not take more than two hours during which no mobile service will be available. After this, the recipient operator has to carry out subscriber verification according to guidelines for acquiring a new user, within five days of receiving a written request. Once verified, the request is forwarded to the donor, seeking its clearance. The donor then has to verify and get back to the recipient with details within two days. MNP is then implemented.

To be able to cope up with the enormous logistics involved, mobile number portability will be carried out by dividing the country into two zones for the purpose of security and reliability. The zones are as shown in the map.


Implications of MNP

The general opinion is that this is a good initiative, but is it really so? We need to consider a few things MNP will impact.

The first and foremost thing to note about MNP is that it will promote healthy competition. Mobile subscribers will no longer be faced with the dilemma whether they should shift to a better operator and lose their mobile number, or to stay dissatisfied with the current one and retain their number. They will now be empowered to go to any operator who they think will serve them better. Effectively, this will stimulate mobile operators to better their services to retain their subscriber base and prevent subscribers from looking towards greener pastures .

This is also like a double-edged sword. It can actually push established mobile operators towards the edge if people start moving towards a newer operator who has nothing to lose and is able to lure subscribers just because of good advertising, and no actual track record.

Postpaid mobile subscribers must have no outstanding bills on the date of application of porting. Prepaid users will lose their balance amount after number porting. Thus, you essentially start off with a clean slate, with the original number.

Though most do not know, the rule is that MNP is available within a telecom circle. This usually means a state. Therefore, you cannot retain your number if you shift from one state to another for change of residence due to your job. (Of course, you can retain your number the old way with expensive national roaming).

It will be impossible to easily ascertain the location of a number. Currently, the first few digits of a mobile number are enough to give you the location of the mobile number as well as its mobile operator. But with MNP in place, the number is not bound to any region or operator, making it very difficult to identify the physical location and telecom operator. Again, as noted in the last point, you can't port number between circles, so as of now at least it would be possible to identify the circle to which a number belongs.

From experiences of mobile subscribers abroad, especially in the UK and New Zealand, the process of changing your mobile number may not exactly be a pleasant ride. Subscribers in these countries have had to endure a lot of hardships owing to MNP. They have had to run between Recipient and Donor operators, re-submitting applications and documents again and again, having to wait for a much longer period for the porting to take place even though it should happen within a stipulated number of days (due to the enormous logistics involved in the process), and also facing with an interim period of uncertainty when you are actually a customer of both operators, thus having to pay monthly rentals to each one of them.

Once having changed your operator retaining the same mobile number, the TRAI directive states that the subscriber has to remain with the new provider for a minimum lock-in period of 90 days before shifting to another provider using MNP. While this sounds fair enough from the operator's point of view so that he gets a fair chance to prove himself , it may be a nightmare for the subscriber if this new operator is even worse than the previous one. However, if you have a quick second thought, you are given the liberty of withdrawing your porting request within 24 hours of the submission of the application. The porting charges will not be refunded.

If you use an iPhone locked to a certain network, then the chances are that you will not be able to use it with another network even though you can technically change your operator keeping the same number. In a similar manner, if you want to move from one technology to another, such as CDMA to GSM or vice versa, the handset won't work due to incompatibility.

To summarize, considering all the pros and cons, mobile number portability is a good thing that is happening and is something that should have been implemented many years ago. As is the usual case with all new technological implementations, there will be hiccups with MNP too. But we surmise that the end result will be good, or at least let us hope for the best.

How many of you would go for MNP? Please do let us know in the comments section below.


Android Developers Blog

Ram's shared items