Tuesday, 31 July 2012

phonegap-powerapp / AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.powerapp"
    android:versionCode="2"
    android:versionName="1.1" >

    <uses-sdk android:minSdkVersion="7" />

    <supports-screens
        android:largeScreens="true"
        android:normalScreens="true"
        android:smallScreens="true"
        android:xlargeScreens="true"
        android:resizeable="true"
        android:anyDensity="true"
        />

    <uses-permission android:name="android.permission.CAMERA" />
    <!-- <uses-permission android:name="android.permission.VIBRATE" /> -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- <uses-permission android:name="android.permission.RECEIVE_SMS" /> -->
    <!-- <uses-permission android:name="android.permission.RECORD_AUDIO" /> -->
    <!-- <uses-permission android:name="android.permission.RECORD_VIDEO"/> -->
    <!-- <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> -->
    <!-- <uses-permission android:name="android.permission.READ_CONTACTS" /> -->
    <!-- <uses-permission android:name="android.permission.WRITE_CONTACTS" /> -->
    <!-- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- <uses-permission android:name="android.permission.GET_ACCOUNTS" /> -->
    <!-- <uses-permission android:name="android.permission.BROADCAST_STICKY" /> -->
    <uses-permission android:name="android.permission.FLASHLIGHT" />

    <application android:debuggable="true" android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity android:configChanges="orientation|keyboardHidden" android:name=".PowerAppActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
      
        <!-- ZXing activities -->
        <activity android:name="com.google.zxing.client.android.CaptureActivity" android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:windowSoftInputMode="stateAlwaysHidden">
            <intent-filter>
                <action android:name="com.phonegap.plugins.barcodescanner.SCAN"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
        <activity android:name="com.google.zxing.client.android.encode.EncodeActivity" android:label="@string/share_name">
            <intent-filter>
                <action android:name="com.phonegap.plugins.barcodescanner.ENCODE"/>
             <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

Monday, 30 July 2012

SMS Messaging in Android

SMS Messaging in Android

In the AndroidManifest.xml file, add the two permissions - SEND_SMS and RECEIVE_SMS:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>
In the main.xml file located in the res/layout folder, add the following code so that the user can enter a phone number as well as a message to send:

<?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="Enter the phone number of recipient"
        />   
    <EditText
        android:id="@+id/txtPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"      
        />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"       
        android:text="Message"
        />   
    <EditText
        android:id="@+id/txtMessage"
        android:layout_width="fill_parent"
        android:layout_height="150px"
        android:gravity="top"       
        />        
    <Button
        android:id="@+id/btnSendSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />  
</LinearLayout>

Next, in the SMS activity, we wire up the Button view so that when the user clicks on it, we will check to see that the phone number of the recipient and the message is entered before we send the message using the sendSMS() function, which we will define shortly:


package net.learn2develop.SMSMessaging;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMS extends Activity
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      

        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);

        btnSendSMS.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {              
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();               
                if (phoneNo.length()>0 && message.length()>0)              
                    sendSMS(phoneNo, message);              
                else
                    Toast.makeText(getBaseContext(),
                        "Please enter both phone number and message.",
                        Toast.LENGTH_SHORT).show();
            }
        });      
    }  
}
The sendSMS() function is defined as follows:

public class SMS extends Activity
{
    //...

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        //...
    }

    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {      
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMS.class), 0);              
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);      
    }  
}

Sunday, 29 July 2012

How to implement voice recognition In Android


Create Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.jameselsey"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="VoiceRecognitionDemo" android:icon="@drawable/icon"
            android:debuggable="true">
        <activity android:name=".VoiceRecognitionDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

And have the following in res/layout/voice_recog.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="4dip"
        android:text="Click the button and start speaking" />

    <Button android:id="@+id/speakButton"
        android:layout_width="fill_parent"
        android:onClick="speakButtonClicked"
        android:layout_height="wrap_content"
        android:text="Click Me!" />

    <ListView android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

 </LinearLayout>



package com.jameselsey;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

/**
 * A very simple application to handle Voice Recognition intents
 * and display the results
 */
public class VoiceRecognitionDemo extends Activity
{

    private static final int REQUEST_CODE = 1234;
    private ListView wordsList;

    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voice_recog);

        Button speakButton = (Button) findViewById(R.id.speakButton);

        wordsList = (ListView) findViewById(R.id.list);

        // Disable button if no recognition service is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0)
        {
            speakButton.setEnabled(false);
            speakButton.setText("Recognizer not present");
        }
    }

    /**
     * Handle the action of the button being clicked
     */
    public void speakButtonClicked(View v)
    {
        startVoiceRecognitionActivity();
    }

    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity()
    {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
        startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * Handle the results from the voice recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
        {
            // Populate the wordsList with the String values the recognition engine thought it heard
            ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                    matches));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

Friday, 27 July 2012

Introducing Android 4.0


Android 4.0 (Ice Cream Sandwich) is the latest version of the Android platform for phones, tablets, and more. It builds on the things people love
most about Android — easy multitasking, rich notifications, customizable home screens, resizable widgets, and deep interactivity — and adds
powerful new ways of communicating and sharing.
Simple, Beautiful, Useful
Refined, evolved UI
Focused on bringing the power of Android to the surface, Android 4.0 makes common actions more visible and lets you navigate with simple,
intuitive gestures. Refined animations and feedback throughout the system make interactions engaging and interesting. An entirely new typeface
optimized for high-resolution screens improves readability and brings a polished, modern feel to the user interface.
Virtual buttons in the System Bar let you navigate instantly to Back, Home, and Recent Apps. The System Bar and virtual buttons are present
across all apps, but can be dimmed by applications for full-screen viewing. You can access each application's contextual options in the Action
Bar, displayed at the top (and sometimes also at the bottom) of the screen.
Multitasking is a key strength of Android and it's made even easier and more visual on Android 4.0. The Recent Apps button lets you jump
instantly from one task to another using the list in the System Bar. The list pops up to show thumbnail images of apps used recently — tapping a
thumbnail switches to the app.
Rich and interactive notifications let you keep in constant touch with incoming messages, play music tracks, see real-time updates from apps,
and much more. On smaller-screen devices, notifications appear at the top of the screen, while on larger-screen devices they appear in the
System Bar.
Home screen folders and favorites tray
New home screen folders offer a new way for you to group your apps and shortcuts logically, just by dragging one onto another. Also, in All Apps
launcher, you can now simply drag an app to get information about it or immediately uninstall it, or disable a pre-installed app.
On smaller-screen devices, the home screen now includes a customizable favorites tray visible from all home screens. You can drag apps,
shortcuts, folders, and other priority items in or out of the favorites tray for instant access from any home screen.
Resizable widgets
Home screens in Android 4.0 are designed to be content-rich and customizable. You can do much more than add shortcuts — you can embed
live application content directly through interactive widgets. Widgets let you check email, flip through a calendar, play music, check social
streams, and more — right from the home screen, without having to launch apps. Widgets are resizable, so you can expand them to show more
content or shrink them to save space.

Thursday, 26 July 2012

how to upload the image into server?


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;

public class sde extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        loadtoUrl("http://
");
    }

    private void loadtoUrl(String string) {

        // TODO Auto-generated method stub
         try {
             String pathToOurFile = "/sdcard/tamil.PNG";
             FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
             BufferedInputStream bis = new BufferedInputStream(fileInputStream,3000);
             byte[] bt=new byte[bis.available()];
            HttpURLConnection connection = (HttpURLConnection)new URL(string).openConnection();
             connection.setDoOutput(true);
             connection.setRequestMethod("POST");
             connection.connect();
            FileOutputStream input = (FileOutputStream) connection.getOutputStream();
            input.write(bt);
        } catch (MalformedURLException e) {
            Context context = null;
            int duration = 0;
            Toast.makeText(context, "erro in writing", duration);
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Wednesday, 25 July 2012

A Simple Android Application For Adding Two Numbers



This is Android application for adding two numbers and displaying their output.Its a beginner level application and the understanding of this code will help in the implementation of other features of a basic calculator.
As we create an android project(Addition) in the eclipse environment,its application framework is defined automatically.We just need to add the code needed for the application.
Firstly modifying the .xml file in addition/res/layout/main.xml which is responsible for the layout of the application.

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADDITION OF NUMBERS"
android:id="@+id/textView1"
android:layout_x="73dip"
android:layout_y="28dip"></TextView>
<TextView android:layout_width="wrap_content"
android:layout_x="36dip"
android:layout_height="wrap_content"
android:text="First Amount"
android:id="@+id/textView2"
android:layout_y="80dip"></TextView>
<EditText android:text=""
android:layout_width="wrap_content"
android:layout_x="172dip"
android:id="@+id/amount1"
android:layout_height="wrap_content"
android:layout_y="62dip"></EditText>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Amount"
android:id="@+id/textView3"
android:layout_x="36dip"
android:layout_y="169dip"></TextView>
<EditText android:text=""
android:layout_width="wrap_content"
android:layout_x="169dip"
android:id="@+id/amount2"
android:layout_height="wrap_content"
android:layout_y="152dip"></EditText>
<Button android:layout_width="wrap_content"
android:id="@+id/calculate"
android:layout_x="41dip"
android:layout_height="wrap_content"
android:text="Calculate"
android:layout_y="232dip"></Button>
<EditText android:text=""
android:layout_width="wrap_content"
android:layout_x="172dip"
android:id="@+id/tt"
android:layout_height="wrap_content"
android:layout_y="232dip"></EditText>
</AbsoluteLayout>

Now modify the addition/src/com.example.addition/addition.java as shown below:(com.example.addition is the package name)
package com.example.addition;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;

public class test extends Activity
{
EditText amount1;
EditText amount2;
TextView tt;
Button calculate;
double x=0;
double y=0;
double z=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
amount1=(EditText)findViewById(R.id.amount1);
amount2=(EditText)findViewById(R.id.amount2);
tt=(TextView)findViewById(R.id.tt);
calculate=(Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) { calculate();}});
}
private void calculate()
{
x=Double.parseDouble(amount1.getText().toString());
y=Double.parseDouble(amount2.getText().toString());
z=x+y;
tt.setText(Double.toString(z));
}
}

Monday, 23 July 2012

Android MotionEvent


Class Overview
Object used to report movement (mouse, pen, finger, trackball) events. Motion events may hold either absolute or relative movements and other data, depending on the type of device.
Overview
Motion events describe movements in terms of an action code and a set of axis values. The action code specifies the state change that occurred such as a pointer going down or up. The axis values describe the position and other movement properties.
For example, when the user first touches the screen, the system delivers a touch event to the appropriate View with the action code ACTION_DOWN and a set of axis values that include the X and Y coordinates of the touch and information about the pressure, size and orientation of the contact area.
Some devices can report multiple movement traces at the same time. Multi-touch screens emit one movement trace for each finger. The individual fingers or other objects that generate movement traces are referred to as pointers. Motion events contain information about all of the pointers that are currently active even if some of them have not moved since the last event was delivered.
The number of pointers only ever changes by one as individual pointers go up and down, except when the gesture is canceled.
Each pointer has a unique id that is assigned when it first goes down (indicated by ACTION_DOWN or ACTION_POINTER_DOWN). A pointer id remains valid until the pointer eventually goes up (indicated by ACTION_UP or ACTION_POINTER_UP) or when the gesture is canceled (indicated by ACTION_CANCEL).
The MotionEvent class provides many methods to query the position and other properties of pointers, such as getX(int), getY(int), getAxisValue(int), getPointerId(int), getToolType(int), and many others. Most of these methods accept the pointer index as a parameter rather than the pointer id. The pointer index of each pointer in the event ranges from 0 to one less than the value returned by getPointerCount().
The order in which individual pointers appear within a motion event is undefined. Thus the pointer index of a pointer can change from one event to the next but the pointer id of a pointer is guaranteed to remain constant as long as the pointer remains active. Use the getPointerId(int) method to obtain the pointer id of a pointer to track it across all subsequent motion events in a gesture. Then for successive motion events, use the findPointerIndex(int) method to obtain the pointer index for a given pointer id in that motion event.
Mouse and stylus buttons can be retrieved using getButtonState(). It is a good idea to check the button state while handling ACTION_DOWN as part of a touch event. The application may choose to perform some different action if the touch event starts due to a secondary button click, such as presenting a context menu.
Batching
For efficiency, motion events with ACTION_MOVE may batch together multiple movement samples within a single object. The most current pointer coordinates are available using getX(int) and getY(int). Earlier coordinates within the batch are accessed using getHistoricalX(int, int) and getHistoricalY(int, int). The coordinates are "historical" only insofar as they are older than the current coordinates in the batch; however, they are still distinct from any other coordinates reported in prior motion events. To process all coordinates in the batch in time order, first consume the historical coordinates then consume the current coordinates.
Example: Consuming all samples for all pointers in a motion event in time order.

void printSamples(MotionEvent ev) {
final int historySize = ev.getHistorySize();
final int pointerCount = ev.getPointerCount();
for (int h = 0; h < historySize; h++) {
System.out.printf("At time %d:", ev.getHistoricalEventTime(h));
for (int p = 0; p < pointerCount; p++) {
System.out.printf(" pointer %d: (%f,%f)",
ev.getPointerId(p), ev.getHistoricalX(p, h), ev.getHistoricalY(p, h));
}
}
System.out.printf("At time %d:", ev.getEventTime());
for (int p = 0; p < pointerCount; p++) {
System.out.printf(" pointer %d: (%f,%f)",
ev.getPointerId(p), ev.getX(p), ev.getY(p));
}
}

Sunday, 22 July 2012

Android Accelerometer Example

Android  Accelerometer Example

The Java Code(HelloAndroid.java)

package com.example.helloandroid;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity implements SensorEventListener {
    private SensorManager sensorManager;

    TextView xCoor; // declare X axis object
    TextView yCoor; // declare Y axis object
    TextView zCoor; // declare Z axis object

    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        xCoor=(TextView)findViewById(R.id.xcoor); // create X axis object
        yCoor=(TextView)findViewById(R.id.ycoor); // create Y axis object
        zCoor=(TextView)findViewById(R.id.zcoor); // create Z axis object

        sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
        // add listener. The listener will be HelloAndroid (this) class
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);

        /*    More sensor speeds (taken from api docs)
            SENSOR_DELAY_FASTEST get sensor data as fast as possible
            SENSOR_DELAY_GAME    rate suitable for games
             SENSOR_DELAY_NORMAL    rate (default) suitable for screen orientation changes
        */
    }

    public void onAccuracyChanged(Sensor sensor,int accuracy){

    }

    public void onSensorChanged(SensorEvent event){

        // check sensor type
        if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){

            // assign directions
            float x=event.values[0];
            float y=event.values[1];
            float z=event.values[2];

            xCoor.setText("X: "+x);
            yCoor.setText("Y: "+y);
            zCoor.setText("Z: "+z);
        }
    }
}

The Layout(main.xml)

Just three text labels, one for each axis.

<?xml version="1.0" encoding="utf-8"?>
<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TableRow>
    <TextView
        android:id="@+id/xcoor"
        android:text="X Coordinate: "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />
    </TableRow>

    <TableRow>
    <TextView
        android:id="@+id/ycoor"
        android:text="Y Coordinate: "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />
    </TableRow>

    <TableRow>
    <TextView
        android:id="@+id/zcoor"
        android:text="Z Coordinate: "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />
    </TableRow>

</TableLayout>

The Manifest(AndroidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.helloandroid"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="13" />
    <uses-permission android:name="android.permission.INTERNET" />

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

        <activity android:name=".HelloAndroid"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Friday, 20 July 2012

Java Program Biggest of 3 Numbers using Logical Operators And Scanner class


Scanner class

The Scanner class is a class in java.util, which allows the user to read values of various types. There are far more methods in class Scanner than you will need in this course. We only cover a small useful subset, ones that allow us to read in numeric values from either the keyboard or file without having to convert them from strings and determine if there are more values to be read.


// Scanner class work with JDK1.5 or above
import java.util.*;
class BiggestThree
{
    public static void main(String args[])
    {      
        int n1, n2, n3, big;
        Scanner scan= new Scanner(System.in);
        System.out.println("Please Enter No 1: ");
        n1=scan.nextInt();
        System.out.println("Please Enter No 2: ");
        n2=scan.nextInt();
        System.out.println("Please Enter No 3: ");
        n3=scan.nextInt();
        if(n1>n2 && n1>n3)
            big=n1;
        else if(n2>n1 && n2>n3)
            big=n2;
        else
            big=n3;
        System.out.println("Biggest No: " + big);
    }
}
    

out put:

Please Enter No 1: 5
Please Enter No 2: 23
Please Enter No 3: 14
Biggest No: 23

Thursday, 19 July 2012

Android Layout

Android Layout

An Android layout is a class that handles arranging the way its children appear on the screen.  Anything that is a View (or inherits from View) can be a child of a layout. All of the layouts inherit from ViewGroup (which inherits from View) so you can nest layouts.  You could also create your own custom layout by making a class that inherits from ViewGroup.

The standard Layouts are:

AbsoluteLayout
FrameLayout
LinearLayout
RelativeLayout
TableLayout


AbsoluteLayout

AbsoluteLayout is based on the simple idea of placing each control at an absolute position.  You specify the exact x and y coordinates on the screen for each control.  This is not recommended for most UI development (in fact AbsoluteLayout is currently deprecated) since absolutely positioning every element on the screen makes an inflexible UI that is much more difficult to maintain.  Consider what happens if a control needs to be added to the UI. You would have to change the position of every single element that is shifted by the new control.

Here is a sample Layout XML using AbsoluteLayout.

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_x="10px"
        android:layout_y="5px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_x="10px"
        android:layout_y="110px"
        android:text="First Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:layout_x="150px"
        android:layout_y="100px"
        android:width="100px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_x="10px"
        android:layout_y="160px"
        android:text="Last Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
        <EditText
        android:layout_x="150px"
        android:layout_y="150px"
        android:width="100px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</AbsoluteLayout>

Wednesday, 18 July 2012

JavaFX

What Is JavaFX?
The JavaFX platform is the evolution of the Java client platform designed to enable application developers to easily create and deploy rich internet applications (RIAs) that behave consistently across multiple platforms. Built on Java technology, the JavaFX platform provides a rich set of graphics and media API with high-performance hardware-accelerated graphics and media engines that simplify development of data-driven enterprise client applications.

Investing in the JavaFX platform provides the following advantages to Java developers and companies that are part of the Java ecosystem:

    Because the JavaFX platform is written in Java, Java developers can leverage their existing skills and tools to develop JavaFX applications.

    Because Java is widely used, it is easy to find experienced Java developers who can quickly become productive building JavaFX applications.

    By using a homogenous set of Java technologies for both the server and the client platforms, the JavaFX platform reduces the risk of investment by reducing the complexity of the business solutions.

    Development costs are also reduced because of the aforementioned advantages.

    The JavaFX platform provides developers with a development framework and runtime environment to create enterprise and business applications that run across multiple platforms that support Java.

See the JavaFX Architecture and Framework document to learn about the JavaFX platform's architecture and key concepts.
A Brief History of JavaFX

At the JavaOne 2007 conference, Sun Microsystems introduced the JavaFX platform to help content developers and application developers to create content-rich applications for mobile devices, desktops, televisions, and other consumer devices. The initial offering consisted of the JavaFX Mobile platform and the JavaFX Script language. Multiple public releases were delivered after the initial announcement; the 1.3 version was released on April 22, 2010.

After Oracle's acquisition of Sun Microsystems, Oracle announced during the JavaOne 2010 conference that support for the JavaFX Script language would be discontinued. However, it was also announced that the JavaFX Script APIs will be ported to Java and would be released as part of the JavaFX 2 product. This announcement meant that the JavaFX capabilities will become available to all Java developers, without the need for them to learn a new scripting language. With this announcement, Oracle has committed to making JavaFX the premier environment for rich client applications.
What's New in JavaFX 2?

The main focus areas for the JavaFX 2 release include the following features, many of which are also described in the JavaFX Architecture and Framework document:

    Java APIs for JavaFX that provide all the familiar language features (such as generics, annotations, and multithreading) that Java developers are accustomed to using. The APIs are designed to be friendly to alternative JVM languages, such as JRuby and Scala. Because the JavaFX capabilities are available through Java APIs, you can continue to use your favorite Java developer tools (such as IDEs, code refactoring, debuggers, and profilers) to develop JavaFX applications.

    A new graphics engine to handle modern graphics processing units (GPUs). The basis of this new engine is a hardware accelerated graphics pipeline, called Prism, that is coupled with a new windowing toolkit, called Glass. This graphics engine provides the foundation for current and future advancements for making rich graphics simple, smooth, and fast.

    FXML, a new declarative markup language that is XML-based and is used for defining the user interface in a JavaFX application. It is not a compiled language and, hence, does not require you to recompile the code every time you make a change to the layout.

    A new media engine that supports playback of the web multimedia content. It provides a stable, low latency media framework that is based on the GStreamer multimedia framework.

    A web component that gives the capability of embedding web pages within a JavaFX application using the WebKit HTML rendering technology. Hardware accelerated rendering is made available using Prism.

    A refreshed browser plug-In for JavaFX 2 that allows the loading of JavaFX applets based on Prism.

    A wide variety of built-in UI controls, which include Charts, Tables, Menus, and Panes. Additionally, an API is provided to allow third parties to contribute UI controls that the user community can use.

    Sample applications that showcase the different features of the JavaFX 2 technology, along with a large number of code samples and snippets.

    An updated doclet used with the Javadoc tool to generate JavaFX API documentation in HTML format. Detailed information on how to use this updated doclet can be found in Using a Doclet with JavaFX.

Tuesday, 17 July 2012

java.util.ArrayDeque


java.util.ArrayDeque class provides resizable-array and implements the Deque interface. Following are the important points about Array Deques:

    Array deques have no capacity restrictions so they grow as necessary to support usage.

    They are not thread-safe; in the absence of external synchronization.

    They do not support concurrent access by multiple threads.

    Null elements are prohibited in the array deques.

    They are faster than Stack and LinkedList.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.
Class declaration

Following is the declaration for java.util.ArrayDeque class:

public class ArrayDeque<E>
   extends AbstractCollection<E>
      implements Deque<E>, Cloneable, Serializable

Here <E> represents an Element, which could be any class. For example, if you're building an array list of Integers then you'd initialize it as

ArrayList<Integer> list = new ArrayList<Integer>();

Class constructors
S.N.    Constructor & Description
1    ArrayDeque()
This constructor is used to create an empty array deque with an initial capacity sufficient to hold 16 elements.
2    ArrayDeque(Collection<? extends E> c)
This constructor is used to create a deque containing the elements of the specified collection.
3    ArrayDeque(int numElements)
This constructor is used to create an empty array deque with an initial capacity sufficient to hold the specified number of elements.
Class methods
S.N.    Method & Description
1    boolean add(E e)
This method inserts the specified element at the end of this deque.
2    void addFirst(E e)
This method inserts the specified element at the front of this deque.
3    void addLast(E e)
This method inserts the specified element at the end of this deque.
4    void clear()
This method removes all of the elements from this deque.
5    ArrayDeque<E> clone()
This method returns a copy of this deque.
6    boolean contains(Object o)
This method returns true if this deque contains the specified element.
7    Iterator<E> descendingIterator()
This method returns an iterator over the elements in this deque in reverse sequential order.
8    E element()
This method retrieves, but does not remove, the head of the queue represented by this deque.
9    E getFirst()
This method retrieves, but does not remove, the first element of this deque.
10    E getLast()
This method retrieves, but does not remove, the last element of this deque.

Java Syntax

    Classes
    There are some kind of errors that might occur during the execution of the program. An exception is an event that occurs and  interrupts the normal flow of instructions. That is exceptions are objects that store the information about the occurrence of errors.
    

    Hello world (First java program)
    Java is a high level programming language and it is used to develop the robust application. Java application program is platform independent and can be run on any operating System
       

    Under Standing the HelloWorld Program
    Class is the building block in Java, each and every methods & variable exists within the class or object. (instance of program is called object ). The public word specifies the accessibility of the class.
    

    Data types, Variables
    The type of value that a variable can hold is called data type. When we declare a variable we need to specify the  type of value it will hold along with the name of the variable.

        Primitive Data Types

         Literals

         Variables

         Declaring and Assigning values to Variables
           

Arrays
In this section you will be introduced to the concept of Arrays in Java Programming language. You will learn how the Array class in java helps the programmer to organize the same type of data into easily manageable format.

     Introduction to Arrays

     Structure of Arrays

     Array Declaration

     Array Initialization

    Array Usage

     Multi-dimensional arrays

    Two-dimensional arrays

    Copying Arrays
    

Control Statements ...

    if
    To start with controlling statements in Java, lets have a recap over the control statements in C++. You must be familiar with the if-then statements in C++. The if-then statement is the most simpler form of control flow statement.
       

    for
    In the world of Java programming, the for loop has made the life much more easier. It is used to execute a block of code continuously to accomplish a particular condition. For statement consists of tree parts i.e. initialization, condition, and iteration.
       

    switch
    Sometimes it becomes cumbersome to write lengthy programs using if and if-else statements. To avoid this we can use Switch statements in Java. The switch statement is used to select multiple alternative execution paths.
       

    while and do-while
    Lets try to find out what a while statement does. In a simpler language, the while statement continually executes a block of statements while a particular condition is true.
       

    Break and Continue Statements
    Sometimes we use Jumping Statements in Java. Using for, while and do-while loops is not always the right idea to use because they are cumbersome to read. Using jumping statements like break and continue it is easier to jump out of loops to control other areas of program flow.
    

Class, Object and Methods

    Class

    Object

    Constructor

    Constructor Overloading
   

Inheritance
To know the concept of inheritance clearly you must have the idea of class and its features like methods, data members, access controls, constructors, keywords this, super etc.

    Simple Inheritance

    Multilevel Inheritance

     Java does not support multiple Inheritance

     super keyword
   

Abstract Methods and Classes
While going through the java language programming you have learned so many times the word abstract. In java programming language the word abstract is used with methods and classes.

    Abstract Method

    Abstract Class
   

Packages
Package is a mechanism for organizing a group of related files in the same directory. In a computer system, we organize files into different directories according to their functionality, usability and category.

    Package categories in Java

    Create Your Own Package

    How to import a package

    Create Subpackages
   

Interface in Java
In this section we will learn about Interface and Marker Interfaces in Java. This tutorial will clarify you questions "What is marker Interface?" and "Why use Marker Interface?" and "difference between abstract class and the interface".

Exception Handling
Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during the program execution. During the program execution if any error occurs and you want to print your own message.....


Input and Output
The Java I/O means Java Input/Output and is a part of java.io package. This package has a InputStream and OutputStream. Java InputStream is  for reading the stream, byte stream and array of byte stream.

    Introduction

    Read Text from Standard IO

    Filter Files in Java

    Java read file line by line

    Create File in Java

    Copying one file to another

    Serializing an Object in Java

    De-serializing an Object in java



Applets
Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it.

    Introduction

    Advantages of Applet

    Disadvantages of Java Applet

    Life Cycle of Applet

    Creating First Applet Example

    Passing Parameter in Java Applet

Sunday, 15 July 2012

General things To learn in Java

    Java as a programming language
    Java is an Object oriented application programming language developed by Sun Microsystems. Java is a very powerful general-purpose programming language.
   

    Java as an Object Oriented Language
    In this section, we will discuss the OOPs concepts along with  fundamentals  used to develop the java applications and programs.
    

    Applications and Applets
    Now a days, Java is widely used for applications and applets. The code for the application in object format resides on the user's machine and is executed by a run-time interpreter.
    

    Peculiarities of Java
    The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language.
    

Java Tools

    Compilers
    To commence with Java programming, we must know the significance of Java Compiler. When we write any program in a text editor like Notepad, we use Java compiler to compile it.

    Interpreter
    We can run Java on most platforms provided a platform must has a Java interpreter. That is why Java applications are platform independent. Java interpreter translates the Java bytecode into the code that can be understood by the Operating System.
   

    Debugger
    Java debugger helps in finding and the fixing of bugs in Java language programs. The Java debugger is denoted as jdb. It works like a command-line debugger for Java classes.
   

    Header file generator
    Firstly, The native methods are in pure C code, not C++. The function prototypes are in an object-oriented form of C which are being provided by javah , but they are still not object methods.
   

    JavaDoc
    Sun Microsystems has provided a computer software tool known as Javadoc. This tool is used to generate API documentation into HTML format from Java source code. It is interesting to know that Javadoc is the industry standard for documenting Java classes.
   

    Applet Viewer
    Applet viewer is a command line program to run Java applets. It is included in the SDK. It helps you to test an applet before you run it in a browser. Before going any further, lets see what an applet is?
       

Java Empowered Browsers
Java language is the most powerful language and is widely used in the web application. So the current versions of most of the web browser are made java enabled. Mostly used java enabled web browsers are:

    Internet Explorer

    Netscape

    HotJava

    Safari

    Firefox 1.0.4

    Mozilla 1.6
   

Installing Java ...
Before getting started developing an application the developer must ensure that he/she is going to develop an application by using  the best tools. The combination of two features Platform Independent and Object Oriented makes the java powerful to build the flexible application.

    Let's start with the Java Development Kit

    JDK Installation

    JDK Installation on Sun Solaris

    JDK Installation on Windows 95 and Windows NT

    JDK installation on Apple Macintosh system 7.5

    Testing the installation

    Exploring the java Developer's kit

    Distributing the Java Virtual Machine

    Other Development Environment

    Summary
      



    Comments
    To comprehend any programming language, there are several kind of comments which are used. These comments are advantageous in the sense that they make the programmer feel convenient to grasp the logic of the program.
   

    Java Keywords
    There are few keywords in Java programming language. Remember, we cannot use these keywords as identifiers in the program. The keywords const and goto are reserved though, they are not being currently used.
    

    Java Data Types
    Data type defines a set of permitted values on which the legal operations can be performed. In java, all the variables needs to be declared first i.e. before using a particular variable, it must be declared in the program for the memory allocation process.
        

    Literals
    By literal we mean any number, text, or other information that represents a value. This means what you type is what you get. We will use literals in addition to variables in Java statement. While writing a source code as a character sequence, we can specify any value as a literal such as an integer.
     

    Operators and Expressions
    Operators are such symbols that perform some operations on one or more operands. Operators are used to manipulate primitive data types. Once we declare and initialize the variables, we can use operators to perform certain tasks like assigning a value, adding the numbers etc.

        Simple Assignment Operators

        Arithmetic Operators

        Unary Operators

        Equality and Relational Operators

        Conditional (Logical) Operators

        Bitwise and Bit Shift Operators

        Type Operators

 

    Operator Precedence
    In Java, Operator Precedence is an evaluation order in which the operators within an expression are evaluated on the priority bases. Operators with a higher precedence are applied before operators with a lower precedence.
     

Friday, 13 July 2012

Java Documentation Comments



Java supports three types of comments. The first two are the // and the /* */. The third type is called a documentation comment. It begins with the character sequence /** and it ends with */.

Documentation comments allow you to embed information about your program into the program itself. You can then use the javadoc utility program to extract the information and put it into an HTML file.

Documentation comments make it convenient to document your programs.
The javadoc Tags:

The javadoc utility recognizes the following tags:
@author    Identifies the author of a class.    @author description
@deprecated    Specifies that a class or member is deprecated.    @deprecated description
{@docRoot}    Specifies the path to the root directory of the current documentation    Directory Path
@exception    Identifies an exception thrown by a method.    @exception exception-name explanation
{@inheritDoc}    Inherits a comment from the immediate superclass.    Inherits a comment from the immediate
Documentation Comment:

After the beginning /**, the first line or lines become the main description of your class, variable, or method.

After that, you can include one or more of the various @ tags. Each @ tag must start at the beginning of a new line or follow an asterisk (*) that is at the start of a line.

Multiple tags of the same type should be grouped together. For example, if you have three @see tags, put them one after the other.

Here is an example of a documentation comment for a class:

/**
* This class draws a bar chart.
* @author Zara Ali
* @version 1.2
*/

What javadoc Outputs?

The javadoc program takes as input your Java program's source file and outputs several HTML files that contain the program's documentation.

Information about each class will be in its own HTML file. Java utility javadoc will also output an index and a hierarchy tree. Other HTML files can be generated.

Since different implementations of javadoc may work differently, you will need to check the instructions that accompany your Java development system for details specific to your version.
Example:
Following is a sample program that uses documentation comments. Notice the way each comment immediately precedes the item that it describes.

After being processed by javadoc, the documentation about the SquareNum class will be found in SquareNum.html.

import java.io.*;

/**
* This class demonstrates documentation comments.
* @author Ayan Amhed
* @version 1.2
*/
public class SquareNum {
   /**
   * This method returns the square of num.
   * This is a multiline description. You can use
   * as many lines as you like.
   * @param num The value to be squared.
   * @return num squared.
   */
   public double square(double num) {
      return num * num;
   }
   /**
   * This method inputs a number from the user.
   * @return The value input as a double.
   * @exception IOException On input error.
   * @see IOException
   */
   public double getNumber() throws IOException {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader inData = new BufferedReader(isr);
      String str;
      str = inData.readLine();
      return (new Double(str)).doubleValue();
   }
   /**
   * This method demonstrates square().
   * @param args Unused.
   * @return Nothing.
   * @exception IOException On input error.
   * @see IOException
   */
   public static void main(String args[]) throws IOException
   {
      SquareNum ob = new SquareNum();
      double val;
      System.out.println("Enter value to be squared: ");
      val = ob.getNumber();
      val = ob.square(val);
      System.out.println("Squared value is " + val);
   }
}

Thursday, 12 July 2012

Java Design Pattern interview Questions and Answers

What is a software design pattern?

Latest answer: A reusable software design solution in general for the problems that are recurrently occuring. Design pattern

is not a solution but a description for how to solve a problem in different situations

What is an analysis pattern?

Latest answer: It is a software pattern which is not related to a language. It is related to a business domain like health care,

telecom

What are the differences between analysis patterns and design patterns?

Latest answer: Analysis pattern are targeted for domain architecture, where as design pattern are targeted for

implementation mechanism for some of the aspects of the domain

What is Singleton pattern?

Latest answer: Singleton pattern is one of the design patterns that is utilized for restricting instantiation of a class to one or

few specific objects.

How do you write a Thread-Safe Singleton?

Latest answer: The following are the steps to write a thread-safe singleton: Declare a Boolean variable, ‘instantiated’, to

know the status of instantiation of a class, an object of Object class and a variable of the same class with initial value as

null

What is the Reactor pattern?

Latest answer: The Reactor pattern is an architectural pattern that allows demultiplexing of event-driven applications and

dispatch service requests which are delivered by one or more application clients to an application
What are Collaboration Patterns?

Latest answer: Repeatable techniques which are utilized by people of different teams for helping them work together. The

really have nothing to do with object-oriented development

What is session facade?

Latest answer: Session Façade is one of the design pattern. It is utilized in developing enterprise applications frequently

What are Anti-Patterns?

Latest answer: A design pattern which obviously appears, but is an ineffective or far from optimal in practice. There must be

atleast two key elements

How do I document a design pattern?

Latest answer: The following are the major points for describing a pattern. Short and meaningful name for the pattern is to be

selected. Problem description and goals and constraints that may occur in that context is to be identified.

Wednesday, 11 July 2012

Java - Methods

Java - Methods

A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println method, for example, the system actually executes several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.
Creating a Method:

In general, a method has the following syntax:

modifier returnValueType methodName(list of parameters) {
  // Method body;
}

A method definition consists of a method header and a method body. Here are all the parts of a method:

    Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.

    Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.

    Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.

    Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

    Method Body: The method body contains a collection of statements that define what the method does.



Note: In certain other languages, methods are referred to as procedures and functions. A method with a nonvoid return value type is called a function; a method with a void return value type is called a procedure.
Example:

Here is the source code of the above defined method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two:

/** Return the max between two numbers */
public static int max(int num1, int num2) {
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result;
}


Here is the code of the program :
class square{
  int sqarea(int side){
  int area = side * side;
  return(area);
  }
  int sqpari(int side){
  int pari = 4 * side;
  return(pari);
  }
}
class rectangle{
  int rectarea(int length,int breadth){
  int area = length * breadth;
  return(area);
  }
  int rectpari(int length,int breadth){
  int pari = 2*(length + breadth);
  return(pari);
  }
}
public class ObjectClass{
  public static void main(String args[]){
  int sarea1,sarea2,pari1,pari2;
  int rectarea1,rectarea2,rectpari1,rectpari2;
  square sq = new square();
  rectangle rect = new rectangle();
  int a=20;
  System.out.println("Side of first square = " + a);
  sarea1 = sq.sqarea(a);
  pari1 = sq.sqpari(a);
  System.out.println("Area of first square = " + sarea1);
  System.out.println("Parimeter of first square = " + pari1);
  a = 30;
    System.out.println("Side of second square = " + a);
  sarea2 = sq.sqarea(a);
  pari2 = sq.sqpari(a);
  System.out.println("Area of second square = " + sarea2);
  System.out.println("Parimeter of second square = " + pari2);
  int x = 10, y = 20;
  System.out.println("Length of first Rectangle = " + x);
    System.out.println("Breadth of first Rectangle = " + y);
  rectarea1 = rect.rectarea(x,y);
  rectpari1 = rect.rectpari(x,y);
  System.out.println("Area of first Rectangle = " + rectarea1);
  System.out.println("Parimeter of first Rectangle = " + rectpari1);
  x = 15;
  y = 25;
  System.out.println("Length of second Rectangle = " + x);
  System.out.println("Breadth of second Rectangle = " + y);
  rectarea2 = rect.rectarea(x,y);
  rectpari2 = rect.rectpari(x,y);
  System.out.println("Area of second Rectangle = " + rectarea2);
  System.out.println("Parimeter of first Rectangle = " + rectpari2);
  }
}

Tuesday, 10 July 2012

How to write a program in Java File Writer


For writing data to a file, the class FileWriter and BufferedWriter are used.

 FileWriter :

 FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed to binary data) to a file. You create a FileWriter by specifying the file to be written to, or optionally, when the data should be appended to the end of an existing file instead of overwriting that file. The FileWriter class creates an internal FileOutputStream to write bytes to the specified file

BufferedWriter :

The BufferedWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays and strings.
The constructor of the FileWriter class takes the file name which has to be buffered by the BufferedWriter stream. The write( ) method of BufferedWriter class is used to create the file into specified directory.

Following code  write data into new file:

out.write(read_the_Buffered_file_name);

Following code creates the object of FileWriter and BufferedWriter:
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);

Lets see an another example that writes the text input by the user using the FileWriter and the BufferedWriter class.
import java.io.*;

public class FileWriter{

  public static void main(String[] args) throws IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Please enter the file name to create : ");
  String file_name = in.readLine();
  File file = new File(file_name);
  boolean exist = file.createNewFile();
  if (!exist)
  {
  System.out.println("File already exists.");
  System.exit(0);
  }
  else
  {
  FileWriter fstream = new FileWriter(file_name);
  BufferedWriter out = new BufferedWriter(fstream);
  out.write(in.readLine());
  out.close();
  System.out.println("File created successfully.");
  }
  }
}