Google+

Thursday, November 10, 2011

Soap Request in android

Well you need to understand what a soap request is made of:.



Code:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
  </soap:Header>
  <soap:Body>
    <m:GetStockPrice xmlns:m="http://www.example.org/stock">
      <m:StockName>Google</m:StockName>
    </m:GetStockPrice>
  </soap:Body>
</soap:Envelope>

The message has a soap:envelope with a soap:header and a soap:body.

The content type of a soap requests is application/soap-xml

Now to send a soap request with Android you have to use a URLConnection and 2 streams.
An inputstream and an outputstream.


Code:
URL u = new URL(url.toString());
URLConnection cnn = u.openConnection();
cnn.setDoOutput(true);
cnn.setDoInput(true);

((HttpURLConnection)cnn).setRequestMethod("POST");
cnn.setRequestProperty("Content-Type", "application/soap-xml; charset=utf-8");
cnn.setRequestProperty("SOAPAction", method);

OutputStream outStream = cnn.getOutputStream();
outStream.write(soapXML);

InputStream in = cnn.getInputStream();

  1. You need to open the URLConnection.
  2. You set the requestMethod to POST.
  3. You set the content-type to application/soap-xml.
  4. You set a SOAPAction header to the method you want to use. (This is not shown on the previous example which I have from wikipedia.)
  5. You write the soapXml envelope to the outputstream.
  6. You read the response from the inputstream.


You can parse the response with an XmlParser if you want to.

I have combined the send and receive code into a class called Webservice. And I made a class called SoapMessage to handle the construction of a Soap envelope.
Then I send the SoapMessage using the send method of the Webservice class and I add an OnReceiveListener to wait for the response.

This is not the most sophisticated method and probably not the most complete method to send and receive Soap messages but it works in android 2.2 perfectly. As SAX Parser not getting proper response.




SAX Parser example coming soon in next Post




source : http://androidforums.com/developer-101/233069-how-create-weservice-client-android.html

Monday, October 3, 2011

How to Create MD5 Hashed Code in Android

Dear Blog Viewer,


What is the MD5 hash?
The MD5 hash also known as checksum for a file is a 128-bit value, something like a fingerprint of the file. There is a very small possibility of getting two identical hashes of two different files. This feature can be useful both for comparing the files and their integrity control.
Let us imagine a situation that will help to understand how the MD5 hash works.
Alice and Bob have two similar huge files. How do we know that they are different without sending them to each other? We simply have to calculate the MD5 hashes of these files and compare them.
MD5 Hash Properties
The MD5 hash consists of a small amount of binary data, typically no more than 128 bits. All hash values share the following properties:
Hash length
The length of the hash value is determined by the type of the used algorithm, and its length does not depend on the size of the file. The most common hash value lengths are either 128 or 160 bits.
Non-discoverability
Every pair of nonidentical files will translate into a completely different hash value, even if the two files differ only by a single bit. Using today's technology, it is not possible to discover a pair of files that translate to the same hash value.
Repeatability
Each time a particular file is hashed using the same algorithm, the exact same hash value will be produced.
Irreversibility
All hashing algorithms are one-way. Given a checksum value, it is infeasible to discover the password. In fact, none of the properties of the original message can be determined given the checksum value alone.
The algorithm was invented by:
Professor Ronald L. Rivest (born 1947, Schenectady, New York) is a cryptographer, and is the Viterbi Professor of Computer Science at MIT's Department of Electrical Engineering and Computer Science. He is most celebrated for his work on public-key encryption with Len Adleman and Adi Shamir, specifically the RSA algorithm, for which they won the 2002 ACM Turing Award.
Simple Code for Android:

public static final String md5Digest(final String text)
{
     try
     {
           // Create MD5 Hash
           MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
           digest.update(text.getBytes());
           byte messageDigest[] = digest.digest();

           // Create Hex String
           StringBuffer hexString = new StringBuffer();
           int messageDigestLenght = messageDigest.length;
           for (int i = 0; i < messageDigestLenght; i++)
           {
                String hashedData = Integer.toHexString(0xFF & messageDigest[i]);
                while (hashedData.length() < 2)
                     hashedData = "0" + hashedData;
                hexString.append(hashedData);
           }
           return hexString.toString();

     } catch (NoSuchAlgorithmException e)
     {
           e.printStackTrace();
     }
     return ""; // if text is null then return nothing
}


Tuesday, September 20, 2011

How to Change Tab Name from Activity in Android

Tabs in the Android work with TabWidgets.
Contained in the tabwidget are relative layouts for each of your tabs which each contain an imageview and a textview.
Tab index will start from 0 and to access the Tab Contents use the following steps.
For Example. if you want to access title of tab
mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title);

the above statement will provide the view (TextView) at this position.

change the text of Tab

TextView v = ((TextView)mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title));


v.setText("My New Title");


Congratulations.
Your text of tab is changed.


Wednesday, September 14, 2011

How to Convert InputStream to String In Java

Here is the Simple method to convert InputStream Object to String Object.


Just Call this method and pass InputStream Object. it return the String






public static String convertStreamToString(InputStream is) throws Exception
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;

    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    is.close();

    return sb.toString();
}

Tuesday, September 13, 2011

How to get Multiple Select List-Box in PHP

Multiple ListBox in HTML will send the array of selected item. 
 
 
 
Sample PHP Code to access the Multiple Selected List-Box Values.
 
<html>
<head>
<title>List Box Form Data</title>
</head>
<body>
     <h3>List Box Form Data</h3>
     <p>Form data passed from the form</p>
    
    <?php
        echo "<p>select: " . $_POST['select']."</p>\n"; 
        echo "<p>listbox: " . $_POST['listbox'] . "</p>\n";
        $values = $_POST['listmultiple'];
        echo "<p>listmultiple: ";
        foreach ($values as $a){
            echo $a;
        }
        echo "</p>\n";
    ?>
</body>
</html>

Friday, September 9, 2011

How to find Android Unique Device ID or UDID - Part 1

Here is the Simple Statement to find Android Device ID which return a String.


String udid = Secure.getString(getContentResolver(), Secure.ANDROID_ID)




Please Note : 
ANDROID_ID is a 64-bit number (as a hex string) that is RANDOMLY GENERATED on the device's first boot and should remain constant for the lifetime of the device.(The value may change if a factory reset is performed on the device.)

Source : Android Documentation

Wednesday, July 27, 2011

How to Install Android SDK

 General Instructions

Prepare your Computer

Download the SDK Starter Package

The SDK starter package is not a full development environment—it includes only the core SDK Tools, which you can use to download the rest of the SDK components (such as the latest Android platform).

(Optional) Install ADT Plug-in for Eclipse

Download platforms and other components

  • Eclipse: Select Window » Android SDK and AVD Manager
  • Windows: Double-click the SDK Manager.exe file at the root of the Android SDK directory
  • Mac or Linux: Open a terminal and navigate to the /tools directory in the Android SDK, then execute ./android

Available Components

By default, there are two repositories of components for your SDK: Android Repository and Third party Add-ons.
The Android Repository offers these components:
  • SDK Tools (pre-installed in the Android SDK starter package) — Contains tools for debugging and testing your application and other utility tools. You can access these in the <sdk>/tools/ directory of your SDK and read more about them in the Tools section of the developer guide.
  • SDK Platform-tools — Contains tools that are required to develop and debug your application, but which are developed alongside the Android platform in order to support the latest features. These tools are typically updated only when a new platform becomes available. You can access these in the <sdk>/platform-tools/ directory. Read more about them in the Tools section of the developer guide.
  • Android platforms — An SDK platform is available for every production Android platform deployable to Android-powered devices. Each platform component includes a fully compliant Android library and system image, sample code, emulator skins, and any version specific tools. For detailed information about each platform, see the overview documents available under the section "Downloadable SDK Components," at left.
  • USB Driver for Windows (Windows only) — Contains driver files that you can install on your Windows computer, so that you can run and debug your applications on an actual device. You do not need the USB driver unless you plan to debug your application on an actual Android-powered device. If you develop on Mac OS X or Linux, you do not need a special driver to debug your application on an Android-powered device. (See Developing on a Device for more information about developing on a real device.)
  • Samples — Contains the sample code and apps available for each Android development platform. If you are just getting started with Android development, make sure to download the samples to your SDK.
  • Documentation — Contains a local copy of the latest multiversion documentation for the Android framework API.

OS Specific Instructions

Linux

ArchLinux

The package android-sdk is included in AUR. No further changes are needed.

Gentoo Linux

  1. emerge dev-util/android-sdk-update-manager
  2. run /opt/android-sdk-update-manager/tools/android
  3. install platform-tools package
  4. ADB will be at /opt/android-sdk-update-manager/platform-tools/adb
  5. Edit your .bashrc file and add this line:
    export PATH="/opt/android-sdk-update-manager/platform-tools/:${PATH}"

Ubuntu Linux

  1. Follow the General Instructions above.
  2. Setup udev.

Mac OS X

Installing the Android SDK

  1. Download the latest version of the Android SDK
  2. Unzip it and move it where needed
    unzip Downloads/android-sdk_r09-mac_86.zip -d~/bin

  3. Open Terminal.app (in /Applications/Utilities)

  4. Edit ~/.profile and append
    export PATH=~/bin/android-sdk_r09-mac_86/platform-tools:~/bin/android-sdk_r09-mac_86/tools:$PATH

  5. Load new .profile
    source .profile

  6. Run Android SDK Manager
    android

  7. Install Components

Installing Eclipse

  1. Download the latest version of Eclipse (Classic or Java Developers are probably best)
  2. Open Terminal.app (in /Applications/Utilities)
  3. Unzip it and move it where needed.
    tar -zxvf Downloads/eclipse-java-helios-SR1-macosx-cocoa-x86_64.tar.gz
    • Optional: Add to PATH. Edit ~/.profile and append export PATH=[eclipse folder]:$PATH then reload source .profile.

  4. Open Eclipse.

  5. Open Preferences, go to Android. Set your SDK location. Click OK.

  6. Go to Help » Install New Software.

  7. Click Add.
    • Name: Google ADT
    • Location: https://dl-ssl.google.com/android/eclipse/

  8. Install pieces that you want.

Windows

  1. Download the latest Android SDK (preferably the zip file not the exe).
  2. Unzip the package to the root of C:\.
    NOTE: This will output a folder called "android-sdk-windows".

  3. Open up the android-sdk-windows folder and launch the SDK Manager.

  4. When you launch the SDK Manager for the first time it will ask for which packages to install. The only package we are concerned with at this time is "Android SDK Platform-tools, revision 6". You can reject all the others if you are not interested in them.

  5. Once that is finished, you will need to install the USB drivers included with the Android SDK.
    1. Click on"Available Packages" on the left.
    2. Expand "Third party Add-ons".
    3. Expand "Google Inc. add-ons".
    4. Check "Google USB Driver package, revision 4".
    5. Installed Selected.

  6. Once that's finished installing, you can close the SDK Manager.

  7. Go to the Control Panel, and select the System Properties (Windows XP) or System (Windows Vista/7).

  8. Select the Advanced settings;
    • Windows XP: Click on the Advanced tab.
    • Windows Vista/7: Click on Advanced system settings on the left.

  9. Click on Environment Variables.

  10. Under the "System variable" section, you will look for "Path". Double-click on it.

  11. In the "Variable values" section, add at the very end the location of the tools & package-tools folder, with a semicolon separating these two paths from the rest, e.g. %SystemRoot%;C:\android-sdk-windows\platform-tools;C:\android-sdk-windows\tools.

  12. On the device, ensure that USB Debugging is enabled (Settings » Applications » Development).

  13. Plug the device into the computer via USB cable. The computer will attempt to install the drivers automatically.

  14. On success, open the command prompt on the computer, and type in the following command to sure everything is setup properly:
    adb devices

  15. If it lists any devices, everything is fine and you are finished. If not, the drivers may not be installed correctly, please continue.

  16. Open the Device Manager.
    1. Right-click on My Computer (Windows XP) or Computer (Windows Vista/7).
    2. Click on Manage.
    3. Click on Device Manager on the left.

  17. You will probably see Unknown Device with ADB listed under it with a yellow exclamation mark.

  18. Right-click on ADB.

  19. Click on "Update Driver Software".

  20. Click on "Browse my computer for driver software".

  21. Click on "Let me pick from a list of device drivers on my computer".

  22. Click on "Have Disk".

  23. Click on "Browse".

  24. Navigate to "C:\android-sdk-windows\extras\google\usb_driver" and select "android_winusb.inf".

  25. Click on "Android ADB Interface".
    NOTE: You will get an Update Driver Warning, click on "Yes".

  26. Once finished installing the driver, open the command prompt on the computer, and type in the following command to sure everything is setup properly:
    adb devices

  27. If it lists any devices, everything is fine and you are finished. If not, you may have further issues and will have to do further research on your own.




source : http://wiki.cyanogenmod.com/wiki/Howto:_Install_the_Android_SDK

The connection to adb is down, and a severe error has occured

Try below steps:
  1. Close the Eclipse if running
  2. Go to the Android SDK tools directory in Command Prompt
  3. type adb kill-server
  4. then type adb start-server
  5. No error message is thrown while starting ADB server, then adb is started successfully.
  6. Now you can start Eclipse again.
It worked for me this way, Eclipse should be closed before issuing these commands.

OR

Open up the Windows task manager, and kill the process named adb.exe, re-launch the Eclipse.

OR

Go to the Folder \android-sdk\platform-tools ; copy the files and paste into folder \android-sdk\tools
Restart the Eclipse

source : http://stackoverflow.com/questions/4072706/the-connection-to-adb-is-down-and-a-severe-error-has-occured

Tuesday, July 19, 2011

Credit Card Number Validation

Informal explanation

The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number. This account number must pass the following test:
  1. Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
  2. Sum the digits of the products (eg, 10 = 1 + 0 = 1, 14 = 1 + 4 = 5) together with the undoubled digits from the original number.
  3. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
Assume an example of an account number "4992739871" that will have a check digit added, making it of the form 4992739871x:
Account number 4 9 9 2 7 3 9 8 7 1 x
Double every other 4 18 9 4 7 6 9 16 7 2 x
Sum together all numbers 64 + x

To make the sum divisible by 10, we set the check digit (x) to 6, making the full account number 49927398716.
The account number 49927398716 can be validated as follows:
  1. Double every second digit, from the rightmost: (1×2) = 2, (8×2) = 16, (3×2) = 6, (2×2) = 4, (9×2) = 18
  2. Sum all the individual digits (digits in parentheses are the products from Step 1): 6 + (2) + 7 + (1+6) + 9 + (6) + 7 + (4) + 9 + (1+8) + 4 = 70
  3. Take the sum modulo 10: 70 mod 10 = 0; the account number is probably valid.


 Sample Code to Check Card No.


public boolean luhnCardValidationMethod(String cardNumber) {
        char[] charArray = cardNumber.toCharArray();
        int[] number = new int[charArray.length];
        int total = 0;
        for (int i = 0; i < charArray.length; i++)
        {
            number[i] = Character.getNumericValue(charArray[i]);
        }

        for (int i = number.length - 2; i > -1; i -= 2)
        {
            number[i] *= 2;

            if (number[i] > 9)
                number[i] -= 9;
        }

        for (int i = 0; i < number.length; i++)
        {
            total += number[i];
        }

        if (total % 10 != 0)
        {
            //TODO if total%10 is not Equals to Zero the Card is Invalid
            return false;
        }

        //TODO Else Card is Valid
        return true;
    }

Source : http://en.wikipedia.org/wiki/Luhn_algorithm



Some More Tips to Check Card Number.

1. Prefix, Length, and Check Digit Criteria

Here is a table outlining the major credit cards that you might want to validate.

CARD TYPE Prefix Length Check digit algorithm
MASTERCARD51-5516 mod 10
VISA413, 16 mod 10
AMEX34
37
15 mod 10
Diners Club/
Carte Blanche
300-305
36
38
14mod 10
Discover601116 mod 10
enRoute2014
2149
15any
JCB316 mod 10
JCB2131
1800
15 mod 10

2. LUHN Formula (Mod 10) for Validation of Primary Account Number

The following steps are required to validate the primary account number:
 
Step 1:
Double the value of alternate digits of the primary account number beginning with the second digit from the right (the first right--hand digit is the check digit.) 

Step 2:
Add the individual digits comprising the products obtained in Step 1 to each of the unaffected digits in the original number. 

Step 3:
The total obtained in Step 2 must be a number ending in zero (30, 40, 50, etc.) for the account number to be validated.
For example
To validate the primary account number 49927398716:
Step 1:
        4     9     9     2     7     3     9     8     7     1     6
              x2           x2         x2          x2          x2 
-----------------------------------------------------------
             18            4            6           16            2




Step 2: 
4 +(1+8)+ 9 + (4) + 7 + (6) + 9 +(1+6) + 7 + (2) + 6
Step 3:
Sum = 70 : Card number is validated
Note: Card is valid because the 70/10 yields no remainder.


Source : http://www.beachnet.com/~hstiles/cardtype.html


Comments Always Welcome..... :)

    Disable Back Key (Button on Device) in Android

    Here is the code to disable device back key in android 
     
     
    Override the onKeyDown activity method. And check for Back Key Event using KeyEvent.KEYCODE_BACK with 
    Key Hit Count using event.getRepeatCount()==0
    
    
    event.getRepeatCount use to get number of time key pressed.
    if the both the condition true call any customized method where your business logic will be there.
    Here I use onBackPressed(); and return nothing.
     
    Note : if you use statement return in onKeyDown Method you will get ERROR
    So better idea is to use any method and write just return. 
     
     
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    
            onBackPressed();
        }
    
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void onBackPressed() {
    
        return;
    }
     
     
     
     
     
    Welcome for All Comments........ :) 
    

    Thursday, June 30, 2011

    SmartPhones by Sachin Shelke ™: How to Create ProgressBar in Android using XML

    SmartPhones by Sachin Shelke ™: How to Create ProgressBar in Android using XML: "How to use progress bar using Layout.xml file follow the steps.... Step : 1 - Create XML with as given below <Line..."

    JSON Data Parsing in Android - Part - 1

    We are discussing the following points to Parse JSON data in android
    • Why JSON Format?
    • Syntax & Structure of JSON Format
    • Relation Between Android  & JSON
    • Steps to Parse JSON data in Android
    • Sample Application
     Why JSON [JavaScript Object Notation] Format?
    • Lightweight data-interchangeable format
    • Text format that is completely language independent and easy to read
    • JSON is
      - A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, Key-Value Pair , or associative array.
      - An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. 


     Syntax & Structure of JSON Format
    • With Normal Object Collection
      Object_Name : {Key1 : Value1 , Key2 : Value2 , Key3 : Value3}

      Example =

      {
            "FileMenu": {
                                     "subMenu":"New","details":"Create New File",
                                     "subMenu":"Open","details":"Open Existing File",
                                     "subMenu":"Save","details":"Save File"
                               }
      }
    • With Array Based Object Collection
      Object_Name : [
                                     {Key1_1 : Value1_1 , Key1_2 : Value1_2 , Key1_3 : Value1_3},
                                     {Key2_1 : Value2_1 , Key2_2 : Value2_2 , Key2_3 : Value2_3}
                            ]

      Example =
      {
            "Menu": {
                               "menu":"File",
                               "value":"File",
                               "popup":{
                                                      "MenuItem":
                                                      [
                                                                   {"subMenu":"New","details":"Create New File"},                                                                            {"subMenu":"Open","details":"Open Existing File"},
                                                                   {"subMenu":"Save","details":"Save File"}
                                                       ]
                                            }
                          }
      }

    Relation Between Android & JSON

    Android already have inbuild JSON libraries. The Following class are used to parse the JSON Object.

        JSONArray          A JSONArray is an ordered sequence of values.
        JSONObject        A JSONObject is an unordered collection of name/value pairs.
        JSONStringer     JSONStringer provides a quick and convenient way of producing JSON text.
        JSONTokener     A JSONTokener takes a source string and extracts characters and tokens from it.




    Steps to Parse JSON Data in Android






    1. Create a JSON Object and Convert JSONString to JSON Object
        JSONObject jsonObject = new JSONObject(jsonDataString);
       
    2. Create a Key based JSONObject.
        JSONObject menuObject = jsonObject.getJSONObject("Menu");

    3. Get the Value
        Log.d("JSON", "Menu = " + menuObject.getString("menu"));
        Log.d("JSON",
    "Value = " + menuObject.getString("value"));





    Android JSON  Example




    public class MainActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
             String myJsonContent = "{\"Menu\": {\"menu\":\"File\",\"value\":\"File\",\"popup\":{\"MenuItem\":[{\"subMenu\":\"New\",\"details\":\"Create New File\"},{\"subMenu\":\"Open\",\"details\":\"Open Existing File\"},{\"subMenu\":\"Save\",\"details\":\"Save File\"}]}}}";
            sampleJsonParser(myJsonContent);
        }

        public void sampleJsonParser(String jsonString) {
            try {
                JSONObject jObject = new JSONObject(jsonString);
                JSONObject menuObject = jObject.getJSONObject("Menu");
                Log.d(
    "JSON", "Menu = " +menuObject.getString("menu"));
                Log.d(
    "JSON", "Value = " + menuObject.getString("value"));
                JSONObject popupObject = menuObject.getJSONObject("popup");
                JSONArray menuitemArray = popupObject.getJSONArray("MenuItem");
                for (int i = 0; i < 3; i++) {
                    Log.d("JSON",
    "Name = " + menuitemArray.getJSONObject(i).getString("subMenu")
                            .toString());
                    Log.d("JSON",
    "Value = " +menuitemArray.getJSONObject(i).getString(
                            "details").toString());
                }
           } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    Download Source Code & SVN Repository



    Check Your Log with  Tag JSON

    Enjoy The Code................




    Don't Forget to Leave Comments....
    Google+