Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Why Java is Secure and Portable ?

The answer is
  BYTECODE.!

Bytecode it the key that makes Java language most secure and Portable.

When you compile your java program then on successful compilation , java compiler (javac) generates a class file with .class extension which contains the Bytecodes of your java program. Now the Bytecodes which are generated are secure and they can be run on any machine (portable) which has JVM.

How to call a web service from Android

By far the easiest way is to use the ksoap2-android API. You need the ksoap2 jar file (with all dependencies) which can be found here and you need to add this to your classpath. In the following sample code we call a free web service, called currency convertor, which has one operation (method) that is is called ConversionRate. If you look at the service dscription (the WSDL file), you will see that this operation takes two parameters, FromCurrency andToCurrency. Lets say that we want to find out the conversion rate from USD to EUR. We implement the following Activity



package gr.panos.caller;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class ConvertorCaller extends Activity {

    public final static String URL = "http://www.webservicex.net/CurrencyConvertor.asmx";
    public static final String NAMESPACE = "http://www.webserviceX.NET/";
    public static final String SOAP_ACTION = "http://www.webserviceX.NET/ConversionRate";
    private static final String METHOD = "ConversionRate";
    private TextView textView;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_convertor_caller);
        textView = (TextView) findViewById(R.id.textView1);
        AsyncTaskRunner runner = new AsyncTaskRunner();
        runner.execute();
    }

     private class AsyncTaskRunner extends AsyncTask<String, String, String>{

         private String resp;

        @Override
        protected String doInBackground(String... params) {
             try {
              SoapObject request = new SoapObject(NAMESPACE, METHOD);
              request.addProperty("FromCurrency", "USD");
              request.addProperty("ToCurrency", "EUR");

              SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
              envelope.dotNet = true;
              envelope.setOutputSoapObject(request);  
              System.out.println("************ I AM SENDING: " + envelope.bodyOut);
               
               HttpTransportSE transport = new HttpTransportSE(URL);
               try {
                 transport.call(SOAP_ACTION, envelope);
               } catch (IOException e) {
                 e.printStackTrace();
               } catch (XmlPullParserException e) {
                 e.printStackTrace();
             }
           if (envelope.bodyIn != null) {
               if (envelope.bodyIn instanceof SoapFault) {
                   String s = ((SoapFault) envelope.bodyIn).faultstring;
                   System.out.println("************ ERROR: " + s);
                   resp = s;
               } else if (envelope.bodyIn instanceof SoapObject) {
                   SoapObject obj = ((SoapObject) envelope.bodyIn); 
                   System.out.println("**** RESPONSE: " +obj);
                    
                   SoapPrimitive root = (SoapPrimitive) obj.getProperty(0);
                   System.out.println("**** CONVERSION RATE: " +root.toString());
                    
                   resp = root.toString();
               }
                    
           }
         } catch (Exception e) {
           e.printStackTrace();
           resp = e.getMessage();
         }
         return resp;
       }

          /**
           * 
           * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
           */
          @Override
          protected void onPostExecute(String result) {
              textView.setText(resp);
          }
     
          /**
           * 
           * @see android.os.AsyncTask#onPreExecute()
           */
          @Override
          protected void onPreExecute() {
          }
          /**
           * 
           * @see android.os.AsyncTask#onProgressUpdate(Progress[])
           */
          @Override
          protected void onProgressUpdate(String... text) {
          }
    }


}



You also need to define a text view in your layout as well as give the activity INTERNET permission in your manifest file.

Write a program with triangle star pattern


How to write a program with triangle star pattern. 



*
* *
* * *



public class triangle {
public static void main(String[] args) {
for(int i=1;i<=3;i++) {
for(int j=3;j>=i; j--) {
System.out.print(" ");
}
for(int k=1;k<=i; k++) {
System.out.print("* ");
}
System.out.print("\n");
}
}

}

Write a program with L shape triangle pattern


*
* *
* * *





public class task1 {


public static void main(String[] args) {


for(int i=1;i<=3;i++) {


for(int j=1;j<=i; j++) {


System.out.print("*");


}

System.out.print("\n");

}

}
}

Exception handling in java



An exception is a condition that is caused by a run-time error . when java interpreter encounter an error such as dividing an integer  by zero, then it creates an exception and throw it informs us that error has occurred. If that exception is not handled or caught , the interpreter will display an error message and terminate the program. If we want to avoid this and program to continue with execution of remaining code, then we should try to catch the exception. This is known as exception handling

                The exception handling consist of two segments , one to detect errors and throw exception and the other to catch exceptions and to take appropriate actions.
Some common exceptions that are occurred during the program  listed as follows

1)ArithmeticException
Caused by math errors like division by zero
2)ArrayStoreException
Caused when a program tries to store the wrong type of data in array

ArrayIndexOutOfBoundException
Caused by bad index of array
FileNotFoundException
Caused when attempt to access a file that is not exist
IOException
Caused by general I/O failure
OutOfMemoryException
When not enough memory to allocate a new object
NullPointerException
Caused by referencing a null object
NumberFormatException
Caused when a conversion between strings and number fails


Syntax for Exception handling code
There is try keyword in java that is used for exception handling . All the statement s which are likely to generate an exception put in try block and catch block is define by catchkeyword that catches the exception thrown by try block.
Syntax is as follows
try{
statement; // generates an exception
}
catch(Exception_type e)
{
Statement //processes the exception
}
More than one catch statement
It is possible to have more than one catch statements in a program corresponding to single try statement. Example is as follows
class test1{
public static void main(String args[]){
int a[]={2,4};
int b=2;
try{
int  x=a[2]/b-a[1];
}
catch(ArithmeticException e){
System.out.println(“Division by zero”);
}
Catch(ArrayIndexOutOfBoundException e)
{
System.out.println(“Array index error”);
}
Catch(ArrayStoreException e)
{
System.out.println(“Array index error”);
}
Int y=a[1]/a[0];
System.out.println(”y = ”  +y);
}
}
Use of Finally statement
Java supports another statement known as finally for exception handling .  finally  block may be added immediately after the try block or after the last catch block. Defining a finally block is guaranteed to execute statement under the finally block  , regardless of whether or not in exception is thrown.
In the above program we may include the last two statements inside a finally block as shown below.
finally
{
Int y=a[1]/a[0];
System.out.println(”y = ”  +y);
}

Loop in java





Looping is used to develop programs which are having some repetitive process. When a particular block of statement have to reapete then loops are used . it makes the programmer job easier , because instead of writing same lines again and again , loop can be used.
 Loop is consist of  two segments one is body and other is exit condition . exit condition is a condition which will end the loop. Means the sequence of statement will reapete until the condition is true.
A looping process have four main steps , which are as follows:
1)      Setting and initialization of a counter
2)      Execution of statements
3)      Test for condition that whether  the condition is true or false
4)      Increment/decrement counter;
Java supports three type of loop statements :
While
Do while
For
While loop:- while loop is an entry-controlled loop statement . at first step the test condition is evaluated , if it is true then the statement is executed and if it is false the exit from loop. After execution of statement again the condition is evaluated and this process is repeated until the condition is true.
Syntax of while
Initialization :
While (test condition){
Body of loop
Increment/decrement
}
Example of while loop
class whileLoop{
                public static void main(String args[]){
int i=0;
while(i<5){
System.out.println(i);
i++;
}
}
}
Output:
0
 1
2
3
4
Do while loop:-
In while loop first condition is tested then body of loop is executed .In in do while loop first the body of loop is executed and then condition is executed. So the minimum chance of execution of while loop is 0 an the minimum chance of execution of do while loop is 1. Because whether the condition is true or false the statement will be executed atleast for one time.
Syntax of do while loop
Initialization
do
{
Body of loop
}
While(test condition)
We can use nested loop that is loop inside loop according to requirement .
class doWhileLoop{
                public static void main(String args[]){
int row, column, x;
row=1;
do{
column =1;
do{
x=row*column;
column=column+1;
}while(column<=3);
System.out.println();
Row=row+1;
}while(row<=3);
}
}
Output
1    2   3
2    4    6
3   6     9

For loop:-
For loop is most widely used loop and very useful loop .because in for loop initialization , condition and increment/decrement are in a single row.
Syntax of for loop
For(initialization; test condition; increment/decrement){
Body of loop
}

Example of for loop:
public class foorloop {
      public static void main(String[] args) {
            for(int i=1;i<=10;i++){
                  System.out.println("2  * " +i + "=" + 2*i );
            }
      }
}

Output
2  * 1=2
2  * 2=4
2  * 3=6
2  * 4=8
2  * 5=10
2  * 6=12
2  * 7=14
2  * 8=16
2  * 9=18
2  * 10=20

We can use nested loops that is loop inside loop as many as required . There is no limit of nesting loops .

If Else statement




If statement is very powerful decision making statement and is used to control the flow of execution of statement .
If we want to execute a statement on some condition .  than we should use the if statement
Syntax  :-
If(Condition){
//Statement
}
Example :-
If(a<b){
System.out.println(a is smaller than b);
}
In above example first it check that if a is less than b only if it is true then next statement will be executed  otherwise no statement will be executed.
If statement can be implemented in the following  ways:-
1.       Simple if statement
2.       If else statement
3.       Else if ladder
4.       Nested if else statement

1)      Simple if statement :-
If (condition){
Statement - block - x
}
                Statement –block – y
                In this is if the condition is true  then statement block x will be executed  and then statement block y will be executed, otherwise the statement  block x will be skipped only statement block y will be executed.
Example :
Class SimpleIf{
Public static void main(String args[]){
Int a=10,b=5;
If(a>b){
System.out.println(“a is greater”);
}
System.out.println(“Thanks for coming”);
}
}
Output:
a is greater
Thanks for coming

IF Else statement:-
If(condition)
{
Statement – block -x
}
else
{
Statement – block – y
}
Statement-z
In this if the condition is true then statement block x will be executed and statement block y will be skipped and then statement z will be executed and condition will false then statement block x will be skipped and statement block y will be executed and statement z will be executed.
Nested  if else:-
If(condition 1){
                If(condition 2){
Statement  -1
}
else{
statement - 2
}
}
else{
statement -3
}
In the above example if condition-1 is false then statement -1 and statement-2  will be skipped and only statement -3 will be executed and if the condition -1 will true then condition-2 will be checked and if condition -2 will be true then statement -1 will be executed otherwise statement -2 will be executed.
Example
Int  a=5;
Int b=10;
Int c=15;
If(a>b){
                If(a>c){
System.out.println(“a is greater”);
}
else{
System.out.println(“c is greater”)
}
}
else{
if(b>c){
System.out.println(“b is greater”);
}
else{
System.out.println(“c is greater”);
}

}
Else if ladder:-  If we want to use multiple decision in our program then we have an another option that is else if ladder.
Syntax:
If(condition 1) {
Statement 1
}
                else if(condition 2){
                Statement 2
}
else if(condition 2){
                Statement 2
}
else{
Statement  3
}
In this all the condition is evaluated from top to down which condition is that statement will be executed if all condition will be false then final else statement will be executed.
Example
If(marks>90){
System.out.println(“First division”)
}
                else If(marks>80){
System.out.println(“Second division”)
}
else If(marks>60){
System.out.println(“Third division”)
}
else {
System.out.println(“Pass”)
}
This will end our if statement

How to Use DateFormat Class in Java


Use getDateInstance to get the normal date format for that country. For example,
import java.text.DateFormat;
import java.util.Date;

public class DateFormatExample {

    public static void main(String[] args) {
        
        Date now = new Date();

        DateFormat defaultDf = DateFormat.getDateInstance();
        DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT);
        DateFormat mediumDf = DateFormat.getDateInstance(DateFormat.MEDIUM);
        DateFormat longDf = DateFormat.getDateInstance(DateFormat.LONG);
        DateFormat fullDf = DateFormat.getDateInstance(DateFormat.FULL);
        
        System.out.println(" 1. " + defaultDf.format(now));
        System.out.println(" 2. " + shortDf.format(now));
        System.out.println(" 3. " + mediumDf.format(now));
        System.out.println(" 4. " + longDf.format(now));
        System.out.println(" 5. " + fullDf.format(now));
    }
}
The output is
 1. Jun 20, 2008
 2. 6/20/08
 3. Jun 20, 2008
 4. June 20, 2008
 5. Friday, June 20, 2008

Use getTimeInstance to get the time format for that country. For example,
import java.text.DateFormat;
import java.util.Date;

public class DateFormatExample {

    public static void main(String[] args) {
        
        Date now = new Date();

        DateFormat defaultDf = DateFormat.getTimeInstance();
        DateFormat shortDf = DateFormat.getTimeInstance(DateFormat.SHORT);
        DateFormat mediumDf = DateFormat.getTimeInstance(DateFormat.MEDIUM);
        DateFormat longDf = DateFormat.getTimeInstance(DateFormat.LONG);
        DateFormat fullDf = DateFormat.getTimeInstance(DateFormat.FULL);
        
        System.out.println(" 1. " + defaultDf.format(now));
        System.out.println(" 2. " + shortDf.format(now));
        System.out.println(" 3. " + mediumDf.format(now));
        System.out.println(" 4. " + longDf.format(now));
        System.out.println(" 5. " + fullDf.format(now));
    }
}
The output is
 1. 10:09:12 PM
 2. 10:09 PM
 3. 10:09:12 PM
 4. 10:09:12 PM EDT
 5. 10:09:12 PM EDT

Use getDateTimeInstance to get a date and time format. For example,
import java.text.DateFormat;
import java.util.Date;

public class DateFormatExample {

    public static void main(String[] args) {
        Date now = new Date();

        DateFormat defaultDf = DateFormat.getDateTimeInstance();
        DateFormat shortDf = DateFormat.getDateTimeInstance(
               DateFormat.SHORT, DateFormat.SHORT);
        DateFormat mediumDf = DateFormat.getDateTimeInstance(
               DateFormat.MEDIUM, DateFormat.SHORT);
        DateFormat longDf = DateFormat.getDateTimeInstance(
               DateFormat.LONG, DateFormat.SHORT);
        DateFormat fullDf = DateFormat.getDateTimeInstance(
               DateFormat.FULL, DateFormat.SHORT);
        
        System.out.println("  1. " + defaultDf.format(now));
        System.out.println("  2. " + shortDf.format(now));
        System.out.println("  3. " + mediumDf.format(now));
        System.out.println("  4. " + longDf.format(now));
        System.out.println("  5. " + fullDf.format(now));
        System.out.println("============================");
        shortDf = DateFormat.getDateTimeInstance(DateFormat.SHORT, 
              DateFormat.MEDIUM);
        mediumDf = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, 
              DateFormat.MEDIUM);
        longDf = DateFormat.getDateTimeInstance(DateFormat.LONG, 
              DateFormat.MEDIUM);
        fullDf = DateFormat.getDateTimeInstance(DateFormat.FULL, 
              DateFormat.MEDIUM);
   
        System.out.println("  6. " + shortDf.format(now));
        System.out.println("  7. " + mediumDf.format(now));
        System.out.println("  8. " + longDf.format(now));
        System.out.println("  9. " + fullDf.format(now));
        System.out.println("============================");
        
        shortDf = DateFormat.getDateTimeInstance(DateFormat.SHORT, 
              DateFormat.LONG);
        mediumDf = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, 
              DateFormat.LONG);
        longDf = DateFormat.getDateTimeInstance(DateFormat.LONG, 
              DateFormat.LONG);
        fullDf = DateFormat.getDateTimeInstance(DateFormat.FULL, 
             DateFormat.LONG);
   
        System.out.println(" 10. " + shortDf.format(now));
        System.out.println(" 11. " + mediumDf.format(now));
        System.out.println(" 12. " + longDf.format(now));
        System.out.println(" 13. " + fullDf.format(now));
        System.out.println("============================");

        shortDf = DateFormat.getDateTimeInstance(DateFormat.SHORT, 
                DateFormat.FULL);
        mediumDf = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, 
                DateFormat.FULL);
        longDf = DateFormat.getDateTimeInstance(DateFormat.LONG, 
                DateFormat.FULL);
        fullDf = DateFormat.getDateTimeInstance(DateFormat.FULL, 
                DateFormat.FULL);
   
        System.out.println(" 14. " + shortDf.format(now));
        System.out.println(" 15. " + mediumDf.format(now));
        System.out.println(" 16. " + longDf.format(now));
        System.out.println(" 17. " + fullDf.format(now));

    }

}
The output is
  1. Jun 21, 2008 9:30:41 PM
  2. 6/21/08 9:30 PM
  3. Jun 21, 2008 9:30 PM
  4. June 21, 2008 9:30 PM
  5. Saturday, June 21, 2008 9:30 PM
============================
  6. 6/21/08 9:30:41 PM
  7. Jun 21, 2008 9:30:41 PM
  8. June 21, 2008 9:30:41 PM
  9. Saturday, June 21, 2008 9:30:41 PM
============================
 10. 6/21/08 9:30:41 PM EDT
 11. Jun 21, 2008 9:30:41 PM EDT
 12. June 21, 2008 9:30:41 PM EDT
 13. Saturday, June 21, 2008 9:30:41 PM EDT
============================
 14. 6/21/08 9:30:41 PM EDT
 15. Jun 21, 2008 9:30:41 PM EDT
 16. June 21, 2008 9:30:41 PM EDT
 17. Saturday, June 21, 2008 9:30:41 PM EDT

Send email in java


How to send email in java


import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class
Mail
{

public static void main(String[] args) {
String[] to = { "example@example.com" };
String[] cc = { "example.example@example.com" };
String[] bcc = { "example@example.com" };
This is for google
Mail.sendMail("example@example.com", "password", to, cc, bcc,
"dont send spams",
"dont send spams..");
}

public synchronized static boolean sendMail(String userName, String passWord, String[] to,
String[] cc, String[] bcc, String subject, String text) {
String starttls = "true";
String auth = "true";
String port="465";
String host="smtp.gmail.com";
String socketFactoryClass="javax.net.ssl.SSLSocketFactory";
boolean debug=true;
String fallback="false";

Properties props = new Properties();
// Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if (!"".equals(port))
props.put("mail.smtp.port", port);
if (!"".equals(starttls))
props.put("mail.smtp.starttls.enable", starttls);
props.put("mail.smtp.auth", auth);
if (debug) {
props.put("mail.smtp.debug", "true");
} else {
props.put("mail.smtp.debug", "false");
}
if (!"".equals(port))
props.put("mail.smtp.socketFactory.port", port);
if (!"".equals(socketFactoryClass))
props.put("mail.smtp.socketFactory.class", socketFactoryClass);
if (!"".equals(fallback))
props.put("mail.smtp.socketFactory.fallback", fallback);

try {
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress("example@example.com"));
for (int i = 0; i < to.length; i++) {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
to[i]));
}
if (cc != null) {
for (int i = 0; i < cc.length; i++) {
msg.addRecipient(Message.RecipientType.CC,
new InternetAddress(cc[i]));
}
}
if (bcc != null) {
for (int i = 0; i < bcc.length; i++) {
msg.addRecipient(Message.RecipientType.BCC,
new InternetAddress(bcc[i]));
}
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
} catch (Exception mex) {
mex.printStackTrace();
return false;
}
}

}

Create database and insert records in it for Android



Create a Database

Simple steps to create a database and handle are as following.
  1. Create "SQLiteDatabase" object.
  2. Open or Create database and create connection.
  3. Perform insert, update or delete operation.
  4. Create Cursor to display data from table of database.
  5. Close the database connectivity.
Following tutorial helps you to create database and insert records in it.

Step 1:
 Instantiate "SQLiteDatabase" objectSQLiteDatabase db;
Before you can use the above object, you must import the android.database.sqlite.SQLiteDatabasenamespace in your application. 
db=openOrCreateDatabase(String path, int mode, SQLiteDatabase.CursorFactory factory) 
This method is used to create/open database. As the name suggests, it will open a database connection if it is already there, otherwise it will create a new one.

Example,

db=openOrCreateDatabase("XYZ_Database",SQLiteDatabase.CREATE_IF_NECESSARY,null);


Step 2: Execute DDL command

db.execSQL(String sql) throws SQLException

This command is used to execute single SQL statement which doesn't return any data means other than SELECT or any other.

db.execSQL("Create Table Temp (id Integer, name Text)");

In the above example, it takes "CREATE TABLE" statement of SQL. This will create a table of "Integer" & "Text" fields.

Try and Catch block is require while performing this operation. An exception that indicates there was an error with SQL parsing or execution.

Step 3:
 Create object of "ContentValues" and Initiate it.ContentValues values=new ContentValues();

This class is used to store a set of values. We can also say, it will map ColumnName and relavent ColumnValue.
values.put("id", eid.getText().toString());          
values.put(
"name", ename.getText().toString()); 
String Key
Name of field as in table. Ex. "id", "name"
String Value
Value to be inserted.
Step 4: Perform Insert Statement.insert(String table, String nullColumnHack, ContentValues values)
String table
Name of table related to database.
String nullColumnHack
If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where yourvalues is empty.
ContentValues values
This map contains the initial column values for the row.
This method returns a long. The row ID of the newly inserted row, or -1 if an error occurred.

Example,
db.insert("temp", null, values);

Step 5:
 Create Cursor

This interface provides random read-write access to the result set returned by a database query.
Cursor c=db.rawQuery(String sql, String[] selectionArgs)


Strign sql
The SQL query
String []selectionArgs
You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
Example,Cursor c=db.rawQuery("SELECT * FROM temp",null);

Methods
 
moveToFirst
Moves cursor pointer at first position of result set
moveToNext
Moves cursor pointer next to current position.
isAfterLast
Returs false, if cursor pointer is not at last position of result set.

Example,c.moveToFirst();while(!c.isAfterLast())
{
     //statement…
c.moveToNext();
}


Step 6:
 Close Cursor and Close Database connectivity

It is very important to release our connections before closing our activity. It is advisable to release the Database connectivity in "onStop" method. And Cursor connectivity after use it.

Introduction to SQLite Database for Android


Now move to Data base ..
we use SQLite for take access on data.


Introduction

In this article, we will see how to create a SQLite database in an Android application. We will also see how to add records to the database and read and display in an application.


SQLiteDatabase

In Android, the SQLiteDatabase namespace defines the functionality to connect and manage a database. It provides functionality to create, delete, manage and display database content. 

Create a Database

Simple steps to create a database and handle are as following.
  1. Create "SQLiteDatabase" object.
  2. Open or Create database and create connection.
  3. Perform insert, update or delete operation.
  4. Create Cursor to display data from table of database.
  5. Close the database connectivity.

LinkWithin

Related Posts Plugin for WordPress, Blogger...