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.


Tuesday, October 26, 2010

Developing / Testing Android applications for MOTOROLA Handsets

Motorola provides lot of supporting tools for developin applications for their android handsets.

They provides more development tools and resources such as SDK Add-ons for targeting Motorola handsets, useful libraries, and sample source code.

visit this link for more information:

http://developer.motorola.com/docstools/

for more Additional Tools & Resources

http://developer.motorola.com/docstools/tools/

You can download SDK's and handset emulators and sample codes .
for installation of SDK addon's
goto this link

http://developer.motorola.com/docstools/library/Installing_the_Motorola_SDK_Add-on/

have a happy development.





Developing Android applications for Samsung GALAXY Tablet

Suppose,you are writing an application which is targeted to SAMSUNG GALAXY TABLET version,unfortunately you don't have a real device.

Developing for Samsung GALAXY Tab is no different from developing for any other Android based device. By utilizing only public APIs provided in the Android SDK and follow the guidelines and tips below, applications will not just work on the GALAXY Tab but also scale correctly.


If you test the application in android 2.2 emulator it was not perfect and if you run the same in real device,you will unexpected results.

In this case,you can test in ORIGINAL samsung galaxy tablet emulator which is avaliable in SAMSUNG developer portal.

It is with a 7” device and a screen resolution of 1024x600 the Samsung GALAXY Tab provides a perfect form factor to optimize applications, by implementing UI and UX enhancements previously not possible.
   
Samsung GALAXY Tab Add-on Installation Guidelines

1) Run AVD Manager on Eclipse IDE.


2) Select Available Packages in the left panel of AVD Manager.


3) Click “Add ADD-on Site” and enter the URL below.


4) Check Samsung GALAXY Tab Add-on packages and click install button.


5) Check Samsung GALAXY Tab Add-on license & Click install button.


6) After downloading and installation of GALAXY Tab Add-on, you should restart ADB (Android Debug Bridge) or Eclipse. 


Now,you can see the installed addon in Installed Packages of AVD manager and in list of targets available.


You can create samsung galaxy tablet emulator by selecting  samsung galaxy as Target device.

And output is as shown below:


Quick Guide Tips:

Samsung GALAXY Tab is a 7” inch device with 1024x600(WSVGA) resolution running Android 2.2 (Froyo). The following guidelines will help developers optimize applications for the best possible user experience.

Make sure that high density display (HDPI) resources are in the application package, as the tablet display requires these resources. Most Android devices are API level 4 or greater. We recommend porting over our application with minSDKVersion=4 or greater. This allows you to add HPDI resources in the application package. If the system cannot find the HPDI resources and android:anyDensity=”true” 

has been set, the existing resources will be scaled which may not give the user the best experience.

The following are values are default for the Samsung Android Tablet:

DeviceMetrics.density = 240
DeviceMetrics.xdpi = 168
DeviceMetrics.ydpi = 168
The density system property value has been set as
[ro.sf.lcd_density]:[240]

When using bitmap resources like advertisement banners, work with your ad vendor to get the correct banner size. Scale the bitmap programmatically by getting the device height and width at runtime as follows:

WindowManager mWMgr =
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
int width = mWMgr.getDefaultDisplay().getWidth();
int height - mWMgr.getDefaultDisplay().getHeight(); 

Android Market filters out applications based on the values specified in the AndroidManifest.xml file. The 7” inch tablet is a “large” screen.
    So, for applications which have minSDKVersion=3, define support-screens tag explicitly as:
 

  Follow the recommended generic compatibility guidelines, such as:
- In XML layout, Use wrap_content, fill_parent
- Use FrameLayout instead of AbsoluteLayout
- NEVER use hard-coding for pixel value, use dip (density independent pixel)
- Use resources according to each density, resolution category.
 
 

Copying Larger database files in ANDROID Application

If you are trying to import or copy an already existing database ( More than 1Mb in size) file to your application then you will certainly get the following error when you are trying to copy the database.

D/asset (909): Data exceeds UNCOMPRESS_DATA_MAX (1424000 vs 1048576) 
 
Due to the fact that there is a file size limit (upto 1 MB) on resources in the raw or assets folders.
 
Finally it indicates that you can not copy the file which is >1 MB into your application at runtime.
 
I faced this problem when i need to import an 1.5 MB database file into application.
I solved in the following way.
 
1) Split the files.  I used the linux split command to split the binary database file 
into a maximum of 1048576 bytes. 
 
The command is:
split inputfile -b 1048576 outfileprefix 
and the files come out as outfileprefixaa, outfileprefixab, etc.  

2)Copy these files into my raw resource folder and set up my code to 
create and then close a database automatically using SQLiteOpenHelper 
and then to run the following method: 
 
 private void copyDatabase() throws IOException{
       
        OutputStream databaseOutputStream = new 
FileOutputStream("/data/data/com.domain.app/databases/app.db");
         InputStream databaseInputStream;
       
        byte[] buffer = new byte[1024];
        int length;
       
        databaseInputStream = 
databaseOpenHelperContext.getResources().openRawResource(R.raw.datafileaa);
        while ( (length = databaseInputStream.read(buffer)) > 0 ) {
            databaseOutputStream.write(buffer);
        }
        databaseInputStream.close();
       
        databaseInputStream = 
databaseOpenHelperContext.getResources().openRawResource(R.raw.datafileab);
        while ( (length = databaseInputStream.read(buffer)) > 0 ) {
            databaseOutputStream.write(buffer);
        }
        databaseInputStream .close();        
        databaseOutputStream.flush();
        databaseOutputStream.close();
    } 
This solution works perfectly.  And it's very fast.  My final database 
size on the emulator is 1424000 bytes (about 1.5 MB).  It copies almost 
instantly.  There is no delay when the application first runs.  However, 
remember that the resource files remain installed, and you've copied the 
data to a database. 
 
Good luck to all you database pre-populators and I hope this helps.  I 
welcome any input and correction to this document as I am no expert and 
may be doing something that isn't kosher in my code. 

By this we can copy a larger file into application database.


 
 
 
 

Wednesday, September 22, 2010

Get IP address of device in android

AIM :Get IP address of device in android
Solution: 

The following method returns the device ip address which is currently used by device irrespective of type of connection ie.,either 3g/wifi/any other.

It returns NULL if there is no network connection.


public static String getipAddress() {
            try {
                for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress=inetAddress.getHostAddress().toString();
                            Log.e("ip address",""+ipaddress);
                            return ipaddress;
                        }
                    }
                }
            } catch (SocketException ex) {
                Log.e("Socket exception in GetIP Address of Utilities", ex.toString());
            }
            return null;
    }

Call the above method wherever you wnat to get ip address as
String ipaddress=getipAddress();

--------------------------

Tuesday, September 7, 2010

Vibrate ,Lock the screen,getPhonenumber in android

Vibrate the Phone


You can vibrate the phone for a specified duration like so: 
(Vibrator) getSystemService(Context.VIBRATOR_SERVICE).vibrate(milliseconds);


You can use the AudioManager to enable and disable silent mode. 
mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
mAudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);  

 to lock the screen in an Android app?

Remember you need to give permissions for it:
and add these lines to code.
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE); 
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); 
lock.disableKeyguard(); 

How to get my telephone number?

add the line uses-permission android:name="android.permission.READ_PHONE_STATE" to the manifest.xml 
 TelephonyManager mTelephonyMgr;
 mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
 String phonenumber= mTelephonyMgr.getLine1Number();


How to hide the title bar(FULL SCREEN MODE ) ?



Add this lines in your code in oncreate() method just before setting setContentView() method.


 requestWindowFeature(Window.FEATURE_NO_TITLE);
 this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN); 


  setContentView(R.layout.main);  


Notification in Android

AIM :  Notification in Android.

SOLUTION



 int NOTIFICATION_ID=1;
 NotificationManager mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


Notification notification = new Notification(R.drawable.icon,"Notify", System.currentTimeMillis());


notification.setLatestEventInfo(getApplicationContext(), "Title", "Description", null);

mManager.notify(NOTIFICATION_ID, notification);; 


 To cancel  the same notification,call 


mManager.cancel(NOTIFICATION_ID);

Turn off / on wifi in android using code


AIM:  To turn on and turn off wifi in android. 


SOLUTION : 
  •  Declare the following in your manifest file. 
< uses-permission android:name="android.permission.ACCESS_WIFI_STATE" / > < uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"/ > < uses-permission android:name="android.permission.CHANGE_WIFI_STATE" / > < uses-permission android:name="android.permission.WAKE_LOCK" / >



  • In  your Activity class
private WifiManager wifiManager;
@Override
public void onCreate(Bundle icicle) { 
       
       // Get the Wifi service from our system
  wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

  // Check the our wifi is currently turned on or turned off  
if(wifiManager.isWifiEnabled()){
    wifiManager.setWifiEnabled(false); // Turn on/off our wifi
  }else{
    wifiManager.setWifiEnabled(true);
  }
}




Tuesday, August 31, 2010

Working With Canvas in Android

 Some Examples to work with Canvas


Drawing a Round Rectangle 


                Path path = new Path();
RectF rect=new RectF(60,  05, 300, 25);
// rectangle with 10 px Radius
path.addRoundRect(rect, 10, 10, Direction.CCW);
canvas.drawPath(path, p);

Drawing a text 

                              Paint p = new Paint();
             p.setColor(Color.WHITE);

                             p.setTextSize(16);
            Typeface tf=Typeface.SANS_SERIF ;
            p.setTypeface(tf);
            p.setFakeBoldText(true);


                            canvas.drawText("Map ", 380, 20,  p);

Drawing a Bitmap Image

        Bitmap mapbmp=BitmapFactory.decodeResource(getResources(), R.drawable.mapicon);
canvas.drawBitmap(mapbmp, 360, 05, p); 




Working With Bitmap Images in Android

  Scaling an Bitmap Image : 
Let suppose you have an image named bar.png in the folder drawable  of your project with size 200 * 200 px. And you wanted to scale it to some size let suppose 400 * 400 px.


Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.bar);
bmp = Bitmap.createScaledBitmap(bmp, 400,400,  true);

Now your image is scaled to 400 * 400 px.

 Rotating an Bitmap Image :  

                Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.bar);
                Matrix mtx = new Matrix();
mtx.postRotate(180);   // rotating 180 degrees clockwise
Bitmap rotatedBMP = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth() ,bmp.getHeight() , mtx, true);  // creating the bitmap image with new angle.

Now , bmp has original image, rotatedBMP has image with 180 degrees rotated.




Friday, August 27, 2010

Lazy Loading of Images in List-view in android

Suppose ,you have a list View in your activity where you have to download the data and corresponding images and show it in the list.

Generally if you download both the data and images once and after  downloading of data you will show it in the list which will take a longer duration particularly depends on net connectivity speed.

For Reducing the time ,first we download the text ie.,names,links except images .we will put the download links in a stack and we will download them after displaying the list-view by using late downloading of images.
First the list will show and images will show in their corresponding position in the list whenever it got downloaded exactly like android market application.
This will reduce the time and we can download as many items we want to show as like working of android market list view.
You can download the sample working project by clicking here Download the full working Project.

Hope it helps you in writing fast applications.

If it doesn't work for you ,please let me know.


ImageCrop in android

AIM: To  crop the Image in android.
Solution:
The main thing  is open gallery with the intent to Crop the image.
as

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
           intent.setType("image/*");
           intent.putExtra("crop", "true");
           intent.putExtra("aspectX", aspectX);
           intent.putExtra("aspectY", aspectY);
           intent.putExtra("outputX", outputX);
           intent.putExtra("outputY", outputY);
           intent.putExtra("scale", scale);
           intent.putExtra("return-data", return_data);
           intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
           intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
           intent.putExtra("noFaceDetection",!faceDetection); // lol, negative boolean noFaceDetection
           if (circleCrop) {
            intent.putExtra("circleCrop", true);
           }
         
           startActivityForResult(intent, PHOTO_PICKED);

You can download the entire project here by clicking DOWNLOAD PHOTO CROP CODE.

If any problems let me know.


Wednesday, August 25, 2010

Show two Buttons at the Bottom of the screen in ANDROID

This Layout will show the two buttons at the bottom irrespective of the top content and screen resolutions.


< RelativeLayout


        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:id="@+id/root"     >

          < LinearLayout
                android:id="@+id/buttons"
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
            >
                < Button
                        android:id="@+id/buttonbefore"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="50"
                        android:text="back"/ >
                  < Button
                        android:id="@+id/buttonnext"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="50"
                        android:text="Next"
                        / >
 < / LinearLayout>
< !-- Content Layout Put as you like -- >
         < ScrollView
                android:layout_above="@id/buttons"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:fillViewport="true"
               >
                   < LinearLayout
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:layout_margin="3px">

                           < TextView
                                android:id="@+id/tv_1"
                                android:layout_width="fill_parent"
                                android:layout_height="wrap_content"
                                android:textStyle="bold"
                                android:text="start! 1111111111...."
                                / >
       
                            
                                android:id="@+id/tv_1"
                                android:layout_width="fill_parent"
                                android:layout_height="wrap_content"
                                android:textStyle="bold"
                                android:text="start! 1111111111...."
                                / >
                             < TextView
                                android:id="@+id/tv_1"
                                android:layout_width="fill_parent"
                                android:layout_height="wrap_content"
                                android:textStyle="bold"
                                android:text="start! 1111111111...."
                                / >

                  < / LinearLayout>
        < / ScrollView>


              

      

JSON parsing in android

 AIM:To parse a Json string in android.
Solution:
 Step 1 ) Declare the json string .

                JSONObject jObject;
String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\",   \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";

Step 2)  convert jString to the jObject by 
              jObject = new JSONObject(jString);
Step 3) Lets extract the menu object by creating a new menu object,
                        JSONObject menuObject = jObject.getJSONObject("menu");
 extract the attributes as follows:
String attributeId = menuObject.getString("id");
Log.i("attributeID:",""+attributeId);
                       String attributeValue = menuObject.getString("value");
                       Log.i("attributeValue:",""+attributeValue);

Ste 4) Final code:


private void JsonParsing() {
JSONObject jObject;
String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\",   \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
try {
jObject = new JSONObject(jString);

JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
System.out.println(attributeId);

String attributeValue = menuObject.getString("value");
System.out.println(attributeValue);

JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");

for (int i = 0; i < 3; i++) {
Log.i("Value",menuitemArray.getJSONObject(i)
.getString("value").toString());
Log.i("Onclick:", menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}



Different Intents to perform some Basic operations In ANDROID


Hi,
The below are some intents and usage of it.

1) Open callHistory
      
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        i.setData(android.provider.Contacts.People.CONTENT_URI);
        i.setType("vnd.android.cursor.dir/calls");
        startActivity(i);

2) play a specified video file from sd card with video player.
  
        File videoFile2Play = new File("/sdcard/nice_movie.mpeg");
        Intent i = new Intent();
        i.setAction(android.content.Intent.ACTION_VIEW);
        i.setDataAndType(Uri.fromFile(videoFile2Play), "video/mpeg");
        startActivity(i);

3) play a specified audio file from sd card with music player.

        File musicFile2Play = new File("/sdcard/some_file.mp3");
        Intent i2 = new Intent();
        i2.setAction(android.content.Intent.ACTION_VIEW);
        i2.setDataAndType(Uri.fromFile(musicFile2Play), "audio/mp3");
        startActivity(i2);

4) some file types and their MIME types

  
































For MIME documentation visit this link HERE.

5)  Open Browser with some website link.

Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("http://google.com"));
startActivity(i);


6) For More intents please visit this link.


If anybody knows any intents please add them as comments.It will be very helpful.


Android Developers Blog

Ram's shared items