Tuesday, September 22, 2009

Copy File From one location to another-BlackBerry

This will copy the file located in “path” to “path1“.Replaces with existing file

public boolean CopyFile(String path,String path1)
    {
        boolean str = false;
        try {
            FileConnection fc = (FileConnection)Connector.open(path, Connector.READ);
            FileConnection fc1 = (FileConnection)Connector.open(path1, Connector.READ_WRITE);
            if(!fc1.exists())
            {
            fc1.create();
            }
            fc1.setWritable(true);
            if(!fc.exists())
            {
                System.out.println("Source File doesn't exist!");
            }

            else
            {
                int size = (int)fc.fileSize();
                InputStream is = fc.openInputStream();
                OutputStream os=fc1.openOutputStream();
                byte bytes[] = new byte[size];
                is.read(bytes, 0, size);
                os.write(bytes);
                os.close();
                is.close();
                return true;
            }
        }
        catch (Exception ioe)
        {
            System.out.println("File Sys Error"+ioe.getMessage());
        }
        return str;
    }

ksoap-Accessing web service with BlackBerry

Check weather given username and password are correct by connecting to remote server.returns true or false according to server response

Add ksoap jar module to your project

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.xmlpull.v1.XmlPullParserException;

public boolean createSoap(String username,String password)
{
    boolean ans=false;
    SoapObject request = new SoapObject("http://tempuri.org/","isValidUser");
     request.addProperty("Username",username);
     request.addProperty("Password",password);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.bodyOut = request;
    envelope.dotNet = true;
    HttpTransport ht = new HttpTransport("http://164.49.254.143:8080/Service.asmx");
    ht.debug = true;
    try {
        ht.call("http://tempuri.org/isValidUser", envelope);     
        if((envelope.getResponse().toString()).equals("true"))
        {
            return true;   
        }
    }
    catch (XmlPullParserException ex)
    {
        Dialog.alert("ex1 "+ex.toString() );
        ex.printStackTrace();
    } catch (IOException ex) {
        Dialog.alert("ex2 " +ex.toString());
        ex.printStackTrace();
    } catch (Exception ex) {
        Dialog.alert("ex3 " + ex.toString());
    }
    return false;
}

Get Bitmap image from file located in SD Card-BlackBerry

In many GUI design purposes we need to get bitmap images from existing files in memory card.This method returns bitmap image of the given file name file must be located in path “file:///SDCard/Themes/

public Bitmap getBitmap(String fileName)
    {
        Bitmap bkBitmap = null;
        try {
                 FileConnection fconn = (FileConnection)Connector.open("file:///SDCard/Themes/"+fileName );
                 InputStream input = null;
                 input = fconn.openInputStream();     
                 int available = 0;
                 available = input.available();
                 int fSz = (int)fconn.fileSize();
                 byte[] data = new byte[fSz];            
                 input.read(data, 0, fSz);
                 EncodedImage image = EncodedImage.createEncodedImage(data,0,data.length);
                 bkBitmap = image.getBitmap();               
            }
        catch(Exception e)
            {
            }
        return bkBitmap;
    }

Monday, September 21, 2009

Run BlackBerry Application without APN -Dynamically add APN from XML file

Most time we need to connect internet and use web services without setting apn.Some times user may use different sim cards and different service providers but application must work with them all without changing

In this dialog box we will display web page content of given url.Here getpage() method and getTag() methods are in my blog so simply you can  use them

String mcc = Integer.toHexString(RadioInfo.getMCC  (RadioInfo.getCurrentNetworkIndex()));
String mnc = Integer.toHexString(RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex())); Dialog.alert(getTag(ReadFile(),mcc+","+mnc));
Dialog.alert(getPage("http://www.google.com"+";deviceside=true;apn="+getTag(ReadFile(),mcc+","+mnc)));//Dialog will display web page content

//New URL is= ("http://www.google.com"+";deviceside=true;apn="+getTag(ReadFile(),mcc+","+mnc))

 

ReadFile Method

public String ReadFile()
{
//This retturns the String in FileName.txt
//File must locate in Src Folder
try {
Class classs = Class.forName("pkgName.className");//Replace package name and class name with your parameters
//Source Package neme and Class name
InputStream is = classs.getResourceAsStream("/test.txt");//test.txt add to your package folder
byte[] data = new byte[is.available()];
is.read(data, 0, is.available());
String c =new String(data);
return c;
}
catch (Exception ioe)
{
Dialog.alert("Error");
return null;
}
}

 

test.txt

This File provides apn according to the values of mcc and mnc

<310,12></310,12>
<310,4></<310,4> verizon
<310,38></310,38>     AT&T
<310,90></310,90>
<310,150></310,150>
<310,680></310,680>
<310,410></310,410>
<310,160>wap.voicestream.com</310,160>
<310,170>wap.voicestream.com</310,170>
<310,260>wap.voicestream.com</310,260>
<310,490>wap.voicestream.com</310,490>
<310,26>wap.voicestream.com</310,26>
<890,126>wap.voicestream.com</890,126>
<413,2>dialogbb</413,2>
<302,720>internet.com</302,720>
<22e2,0></22e2,0>

Friday, September 18, 2009

Extract variable from XML String - java Blackberry

XML s are basically organize as <tagname>contentent</tagname>

some times we need to get the content of the tag.but in blackberry there no specified method to do that.so use this methods.what we have to do is pass xml string and parameter nane to gettag method then you will get the content between tags

public static String getTag(String XML,String TagName)
{
    try {
        String ans = "error";
        String front1 = "<" + TagName;
        String back1 = "=";
        String[] sssnew = split(XML, front1);
        if (sssnew.length > 1) {
            String[] sss1new = split(sssnew[1], back1);
            if ((sss1new[0]).compareTo(" i:nil") < 1) {
                ans = "";
                return ans;
            }
        }
        String front = "<" + TagName + ">";
        String back = "</" + TagName + ">";
        String[] sss = {};
        sss = split(XML, front);
        if (sssnew.length > 1) {
            String[] sss1 = {};
            sss1 = split(sss[1], back);
            ans = sss1[0];
        }
        return ans;
    } catch (Exception e) {
        return "";
    }
}
private static String[] split(String inString, String delimeter)
{
    String[] retAr = new String[0];
    try {
        Vector vec = new Vector();
        int indexA = 0;
        int indexB = inString.indexOf(delimeter);

        while (indexB != -1) {
            if (indexB > indexA)
                vec.addElement(new String(inString
                        .substring(indexA, indexB)));
            indexA = indexB + delimeter.length();
            indexB = inString.indexOf(delimeter, indexA);
        }
        vec.addElement(new String(inString.substring(indexA, inString
                .length())));
        retAr = new String[vec.size()];
        int intIteration = vec.size();
        for (int i = 0; i < intIteration; i++) {
            retAr[i] = vec.elementAt(i).toString();
        }
    } catch (Exception e)
    {

    }
    return retAr;
}

Interrupt service routine handler- programmable Integrated circuit

 

When trigger switch connected to int/RB0 that will start counting 0 to 10 we can get out put from RA0 toRA3 as 0000 to 1010 use with pic = 16F84

org 0x00                     ;This is where we come on power up and reset

;*******************SETUP CONSTANTS*******************
INTCON         EQU 0x0B       ;Interrupt Control Register

PORTB           EQU 0x06       ;Port B register address

PORTA          EQU 0x05       ;Port A register address

TRISA         EQU 0x85       ;TrisA register address

TRISB            EQU 0x86       ;TrisB register address

STATUS          EQU 0X03      ;Status register address

COUNT          EQU 0x0c         ;This will be our counting variable

TEMP              EQU 0x0d      ;Temporary store for w register

  goto    main                              ;Jump over the interrupt address

;***************INTERRUPT ROUTINE***************

  org                  0x04                ;This is where PC points on an interrupt

  movwf TEMP              ;Store the value of w temporarily

incf                  COUNT,1       ;Increment COUNT by 1, and put the result

;back into COUNT

movlw 0x0A               ;Move the value 10 into w

subwf              COUNT,0       ;Subtract w from COUNT, and put the

;result in w

btfss                STATUS,0       ;Check the Carry flag. It will be set if

                                                ;COUNT is equal to, or is greater than w,

                                                ;and will be set as a result of the subwf

                                                ;instruction

goto                carry_on           ;If COUNT is <10, then we can carry on

goto                clear                 ;If COUNT is >9, then we need to clear it

carry_on

bcf                  INTCON,0x01 ;We need to clear this flag to enable

  ;more interrupts

movfw TEMP              ;Restore w to the value before the interrupt

  retfie                                      ;Come out of the interrupt routine

clear

clrf                  COUNT          ;Set COUNT back to 0

bcf                  INTCON,1      ;We need to clear this flag to enable

                                                ;more interrupts

retfie                              ;Come out of the interrupt routine

;*******************Main Program*********************

main

;*******************Set Up The Interrupt Registers****

bsf                   INTCON,7      ;GIE – Global interrupt enable (1=enable)

bsf                   INTCON,4      ;INTE - RB0 Interrupt Enable (1=enable)

bcf                  INTCON,1      ;INTF - Clear FLag Bit Just In Case

;*******************Set Up The Ports******************

  bsf                STATUS,5     ;Switch to Bank 1

movlw 0x01           

movwf TRISB              ;Set RB0 as input

movlw 0x10                       

movwf TRISA              ;Set R 0 to RA3 on PortA as output

  bcf                  STATUS,5  ;Come back to Bank 0

;*******************Now Send The Value Of COUNT To Port A           

loop

movf                 COUNT,0       ;Move the contents of Count into W

movwf              PORTA           ;Now move it to Port A

goto                 loop                 ;Keep on doing this

end                                           ;End Of Program

 

image

if you need more details go to http://www.mstracey.btinternet.co.uk

There many more things about pic and interrupt service routine .This works for me with Mplab ide and proteous 7 environment

Nuwan added this:

1. You use RC OSC and no capacitor. (R1 and OSC1) This is ok with some pic's but, some are fail. You use distributed capacitance of Rosc pin and it is better to connect 20pF cap to ground.


2. RB0 ,Int 0 RC low pass filter R2 value is too large. Use between 2K ~ 10K value.

Wednesday, September 16, 2009

Send text message from mobile device to computer-java mobile socket level Programming

In many projects we need to communicate mobile device and computers this code demonstrates how to communicate between them.here we have 2 codes one for mobile device and other for java server.server basically keep socket open and listen to that socket and mobile device get text from user and send them to server.this works perfectly with blackberry mobile device and if we can make few changes then able to work with any mobile device.use same host name and port number for both codes.server code add to netbeans project and run it.then mobile client project add to eclipse mobile project and run it.that's it

Server code

import java.net.*;
import java.io.IOException;
import java.io.*;
import java.util.Scanner;

public class Main {
    private static ServerSocket serverSocketin;
    private static ServerSocket serverSocketout;
    public static void main(String[] args)
    {
        try

        {
            serverSocketin = new ServerSocket(8206);
            serverSocketout = new ServerSocket(8207);
            DataSender dtsender = new DataSender();
            DataRiciver dataRiciver=new DataRiciver();
            dtsender.start();
            dataRiciver.start();
        }

         catch (IOException e)

        {
            e.printStackTrace();
        }
    }
    static class DataRiciver extends Thread
    {
        public void run(){
            while (true){
                try {
                    Socket incoming = serverSocketin.accept();
                    DataInputStream in = new DataInputStream(incoming.getInputStream());
                    String data="";
                    data = in.readLine();
                    System.out.println(data);
                    in.close();
                    incoming.close();
                     Thread.sleep(1000);
                }

                catch (Exception e)

                  {
                  }
        }

        }
    }

    static class DataSender extends Thread
    {
        public DataSender()
        {

        }

        public void run()
        {
            while (true)
            {
                try {
                    Scanner reader = new Scanner(System.in);
                    String data = reader.nextLine();
                    Socket outgoing = serverSocketout.accept();
                    PrintStream out = new PrintStream(outgoing.getOutputStream());
                    data=data+ "\n";
                    out.write(data.getBytes());
                    out.flush();
                    out.close();
                    outgoing.close();
                    Thread.sleep(1000);
                }
                catch (Exception ioe)
                {
                }
            }
        }
    }

}

 

Mobile client Code-BlackBerry

import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.MainScreen;
import javax.microedition.io.*;
import java.io.*;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
public class sss extends UiApplication
{
    public static void main(String[] args)
    {
        sss theApp = new sss();
        theApp.enterEventDispatcher();
    }
    public sss()
    {
        pushScreen(new UserInterfaceScreen());
    }
}

final class UserInterfaceScreen extends MainScreen
{
HorizontalFieldManager _fieldManagerTop;
VerticalFieldManager _fieldManagerMiddle;
HorizontalFieldManager _fieldManagerBottom;
BitmapField _bitmap;
Bitmap _canadaImage;
LabelField _label;
BasicEditField _input;
String _canadaCapital;
int displayed = 0;
    public UserInterfaceScreen()
    {
        super();
        LabelField title = new LabelField("Send Text To server",
        LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
        setTitle(title);
        _fieldManagerTop = new HorizontalFieldManager();
        _fieldManagerMiddle = new VerticalFieldManager();
        _fieldManagerBottom = new HorizontalFieldManager();
        add(_fieldManagerTop);
        add(new SeparatorField());
        add(_fieldManagerMiddle);
        add(new SeparatorField());
        add(_fieldManagerBottom);
        _canadaImage = Bitmap.getBitmapResource("canada.png");
        _bitmap = new BitmapField();
        _bitmap.setBitmap(_canadaImage);
        _fieldManagerTop.add(_bitmap);
        _canadaCapital = "txt";
        _label = new LabelField("Please press a button!");
        _input = new BasicEditField("Enter text here: ","ssss");
        _fieldManagerMiddle.add(_label);
        _fieldManagerMiddle.add(_input);
FieldChangeListener listenerCanada = new FieldChangeListener()
        {
            public void fieldChanged(Field field, int context)
            {
                _bitmap.setBitmap(_canadaImage);
                _input.setText(_canadaCapital);
                displayed = 0;
            }
        };
//add button
ButtonField canadaButton = new ButtonField("send");
canadaButton.setChangeListener(listenerCanada);
_fieldManagerBottom.add(canadaButton);

};
protected void makeMenu(Menu menu, int instance) {
menu.add(_changeCapital);
menu.add(_close);
}

private MenuItem _changeCapital = new MenuItem("Send to Server", 110,10)
{
public void run()
{
//=====================================================
//This code block do client task this part can use with any mobile device
//with few changes
try {
    StreamConnection conn;
    conn = (StreamConnection)Connector.open("socket://localhost:8206;deviceside=true");
    //open and connect to server socket use your host name and socket here
    PrintStream output = new PrintStream(conn.openOutputStream());
    String data=_input.getText();;
    //get input text from the user
    output.write(data.getBytes());
    //write to out put
    output.flush();
    output.close();
    conn.close();
    }
catch (Exception e)
    {
    }
//===================================================
}
};

private MenuItem _close = new MenuItem("Close", 110, 10)
{
    public void run()
    {
        onClose();
    }
};

public boolean onClose()
{
    Dialog.alert("Goodbye!");
    System.exit(0);
    return true;
}

}

Mobile Code –java Mobile

package client;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class MobileClient extends MIDlet implements CommandListener {
    private Display display;
    private Command exit;
    private Command send;
    //private Command back;
    private TextBox textBox;

    ServerListner serverListner = new ServerListner();

    public MobileClient() {

        display = Display.getDisplay(this);
        send=new Command("Send",Command.SCREEN,1);
        exit = new Command("Exit", Command.EXIT, 2);

        textBox = new TextBox("Recived massage", "no massage", 81, 0);
        textBox.addCommand(send);
        textBox.addCommand(exit);
        textBox.setCommandListener(this);

        //output=new PrintStream(connection.openOutputStream());

    }

    protected void startApp() throws MIDletStateChangeException {
        display.setCurrent(textBox);
        serverListner.start();

    }

    protected void pauseApp() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    protected void destroyApp(boolean b) throws MIDletStateChangeException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command == exit) {
            try {
                destroyApp(false);
                notifyDestroyed();
            } catch (MIDletStateChangeException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        else if(command ==send)
        {
            String data=textBox.getString();
            sendData(data);
        }
    }

    public void sendData(String data) {
        try {
            StreamConnection connection = (StreamConnection) Connector.open("socket://localhost:8206");
            PrintStream output = new PrintStream(connection.openOutputStream());
            data=data +"\n";
            output.write(data.getBytes());
            output.flush();
            output.close();
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    class ServerListner extends Thread {

        public void run() {
            try {
                while (true) {
                    StreamConnection connection = (StreamConnection) Connector.open("socket://localhost:8206");
                    InputStream in = connection.openInputStream();
                    StringBuffer buffer = new StringBuffer();
                    int ch;
                    while ((ch = in.read()) != -1) {
                        if (ch != '\n') {
                            buffer.append((char)ch);
                        } else {

                        }
                    }
                    textBox.setString(buffer.toString());
                    display.setCurrent(textBox);

                    // connection.close();
                    in.close();
                    connection.close();
                     Thread.sleep(1000);
                }
            } catch (Exception ie) {
                ie.printStackTrace();
            }
        }
    }
}

Tuesday, September 15, 2009

Add APN to your Application in BlackBerry Device-you can access to network from anywhere in the world with any service provider without resetting APN

This Method returns Correct APN to user at run time

public String Getapn()
{

String apn=””;

//is there any other apns add them to following array by replacing empty strings

String[] arr= {"","internet.com","blackberry.net","internet2.voicestream.com","wap.voicestream.com","dialogbb",""};
int i=0;
int j=0;
while(i==1&&j<6)
{
j=j+1;
try
{

//test sending request to google.com here get page method you will find in

//my blog that basically returns page of given address
getPage("http://www.google.com"+";trustAll;deviceside=true;apn="+arr[j]);
i=1;
}
catch (Exception e)
{
}
}
apn=arr[j];

return apn;
}

Monday, September 14, 2009

Simplest Way to VOIP Set Up

This document is about setup voip using open source packages

Building your own corporate phone system using the Asterisk open source telephony suite could result in massive cost savings for your company

Downloading Asterisk/Dahdi/LibPRI

Go to http://www.asterisk.org/downloads and download Asterisk/Dahdi/LibPRI (Look for Asterisk downloads  on right-hand side) .
You can use wget command to download sources (tar ball) on your local directory.
For example:

#>wget http://downloads.digium.com/pub/telephony/dahdi-linux/dahdi-linux-2.0.0.tar.gz
#>wget http://downloads.digium.com/pub/telephony/dahdi-tools/dahdi-tools-2.0.0.tar.gz
#>wget http://downloads.digium.com/pub/libpri/releases/libpri-1.4.7.tar.gz
#>wget http://downloads.digium.com/pub/asterisk/releases/asterisk-1.6.0.1.tar.gz

Installing Asterisk/Dahdi/Libpri

  1. Dahdi Installation
    Download Dahdi into arbitrary directory (/usr/src) and  untar it.
    #>tar xvfz dahdi-linux-<version>
    #>tar xvfz dahdi-tools-<version>
    #>cd dahdi-<version>
    #>make
    #>make install
    #>cd ..
    #>
    cd dahdi-tools-<version>
    #>./configure
    #>make
    #>make install
  2. LibPRI Installation
    Download libpri into arbitrary directory (/usr/src) and untar it.
    #>tar xvfz libpri-<version>
    #>cd libpri-<version>
    #>make
    #>make install
  3. Asterisk Installation

    If you are upgrading Asterisk make sure that old asterisk modules are removed from /usr/lib/asterisk/modules
    #> cd /usr/lib/asterisk
    #> mv modules modules.old
    Download Asterisk into arbirary directory  (/usr/src/) and untar it.
    Untar Asterisk and proceed with installation
    #>tar xvfz asterisk-<version>.tgz
    #>cd asterisk-<version>
    #>./configure
    #>make
    #>make install
    #>make samples (in case of very first install)

Please note: <version> refers to the specific release of your program. For instance, dahdi-linux-2.0.0.tar.gz, once untarred will create the folder dahdi-linux-2.0.0.

When the system comes back up, Asterisk should start automatically. To check that everything is working, check DAHDI is loaded by opening a terminal window and, with root privileges, typing:

# lsmod | grep dahdi

You should see references to several dahdi modules, including dahdi_dummy, dahdi_transcode, crc_ccitt, and dahdi_voicebus.

Check Asterisk is running and log on to the Asterisk command line with:

#asterisk –r

You should see some version and license information along with a "Connected to Asterisk" message and prompt.

To stop asterisk from the Asterisk command line type

CLI> stop now

or from the Linux command prompt type

# service asterisk stop


Setting up an X-Lite client on Asterisk

X-Lite and Asterisk Ver 1.00 Page 1
1) Adding a client entry to Asterisk’s SIP configuration
* edit the SIP configuration file /etc/asterisk/sip.conf
% sudo vi /etc/asterisk/sip.conf
*enter an entry for each X-Lite client, for example
[12345] ; X-Lite client 12345
type=friend
secret=blah
auth=md5
nat=yes ; we assume clients are behind NAT
host=dynamic ; and have dynamic IP addresses
reinvite=no ; if so, we need to make them
canreinvite=no ; always go through Asterisk
qualify=1000
dtmfmode=inband
callerid="Fred Flintstone" <12345>
disallow=all
allow=gsm ; add whatever other codecs we fancy
context=theflintstones ; use a context that exists ;-)
*save the changes
2) Adding extensions for X-Lite clients
* edit the Extensions configuration file /etc/asterisk/extensions.conf
% sudo vi /etc/asterisk/extensions.conf
*enter one catch-all extension, for example
[theflintstones] ; Our context for X-Lite clients
;
; Catch all five digit numbers, no leading zeroes
exten => _[123456789]XXXX,1,NoOp(“call for “${EXTEN})
exten => _[123456789]XXXX,2,Dial(SIP/${EXTEN},60,tr)
exten => _[123456789]XXXX,3,Congestion
* alternatively, enter one specific extension for each client
* save the changes
3) Reload the new configuration
* on the Asterisk console, reload the configuration files
switch1*CLI> reload

Thursday, September 10, 2009

Add APN to http request automatically for BlackBerry device

Add this to the url As follows
you can add this part to url
URL+";trustAll;deviceside=true;apn=APN"

ex: get APN from mobile service provider
and add to above code

Monday, September 7, 2009

Find Distance Between 2 Cities Using Google Map

Copy This Code to file named main.html and save it

Then open with any web browser

//===========================================================

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  <head>
<title>Google Maps Find Distance</title>
<script src="http://maps.google.com/maps?file=api&;v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
<script type="text/javascript">
   var geocoder, city1, city2;
    function initialize()
    {
      geocoder = new GClientGeocoder();
      //Creates a new instance of a geocoder that talks directly to Google servers.
    }
    function showLocation()
    {
       geocoder.getLocations(document.forms[0].address1.value, set1);
      //set1 method calls then get the address 1.if only location 1 get correct way
      //then only we can get the second address.else display error message
       //getLocations(java.lang.String address, GGeocodeAdvancedResultListener result)
      //getLocations(address, callback) none Sends a request to Google servers to geocode the specified address.
      //getLatLng(address, callback) none Sends a request to Google servers to geocode the specified address. If the
      //address was successfully located, the user-specified callback function is invoked with a GLatLng point. Otherwise,
      //the callback function is given a null point. In case of ambiguous addresses, only the point for the best match is passed to the callback function.
   }
   function calculateDistance()
    {
        try
        {
           var glatlng1 = new GLatLng(city1.lat, city1.lon);
          var glatlng2 = new GLatLng(city2.lat, city2.lon);
           var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
            var kmdistance = (miledistance * 1.609344).toFixed(1);
           document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + city1.address + '<br /><strong>Address 2: </strong>' + city2.address + '<br /><strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
        }
        catch (error)
        {
            alert(error);
        }
   }
  
      function set1(response)
       {
    //200 OK
       //Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request,
    //the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity
    //describing or containing the result of the action.
           if (!response || response.Status.code != 200)
        {
            alert("Sorry, we were unable to geocode the first address");
            //messages
        }
          else
        {
            //set the 1st location only get correct response
            city1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
             //.if only location 1 get correct way then only we can get the second address.else display error message
             geocoder.getLocations(document.forms[0].address2.value, set2);
        }
        }
  
    function set2(response)
            {
                if (!response || response.Status.code != 200)
                {
                    alert("Sorry, we were unable to geocode the second address");
                }
                else
                {
                    //set the 2nd location coordinates
                    city2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                    //when both address get in correct way then we can calculate the distance
                    calculateDistance();
                    load();
                    addToMap(response);
                }
            }
function GoToNext()
{
window.location.href = 'map.html';
//go to next page
}

function help()
{
window.location.href = 'help.html';
//go to next page
}
   </script>
  </head>

  <body onload="initialize()">

    <form action="#" onsubmit="showLocation(); return false;">
  <h1 align="center"><font color="#CC0033" size="5" face="Geneva, Arial, Helvetica, sans-serif">Find
    Distance Between 2 Cities Using Google Map</font></h1>
  <h1><font color="#00FF33" size="4" face="Courier New, Courier, mono"></font></h1>
  <p><font color="#0066CC" size="4" face="Verdana, Arial, Helvetica, sans-serif">by:S.R.B.
    Malalgoda</font><font color="#00FF33" size="4" face="Courier New, Courier, mono">
    </font></p>
  <p>
    <input type="text" name="address1" value="" class="address_input" size="40" />
    <input type="text" name="address2" value="" class="address_input" size="40" />
  </p>
  <p>
    <input type="submit" name="find" value="Calculate Distance" /><p><input type="submit" value="View Map" onClick="GoToNext()"
  <p>
  </p>
   </form>
    <p id="results"></p>

</body>
</html>

Sunday, September 6, 2009

Simplest Way to save data in mysql database and text file using PHP

//==============================================

C:\wamp\www\saveD\  Used as project folder

This Code creates database and tables automatically when its load first time

I use wamp server to run program

//=============================================

index.php

This use to create database and tables and prompt user to add data

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
//Creatr Database Dinamically in run time
//Make Connection To Database in Local host
//Username=root and Password=""
//This is the basic way in Xamp & Wamp
$connect =mysql_connect("localhost","root","") or die(mysql_error());
//mysql_select_db("eee");
$quary="create database db1";
//Create Database named DB1
$quary1="use db1";
//Use db1
$quary2="create table table1(timeA int,timeB int,timeC int,timeU varchar(8))";
//Creates Table named table1
//Executes queries
$results = mysql_query($quary);
$results1 = mysql_query($quary1);
$results2 = mysql_query($quary2);
if($results2==1)
{
echo "create table succesfully";
}
else
{
echo "Already Exsists";
}
?>
<form name="form1" method="post" action="insert.php">
  <input type="submit" name="Submit" value="Insert Values">
</form>
<p>&nbsp;</p>
</body>
</html>

//========================================================

insert.php

This use to take input and post them to save page

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form action="save.php" method="post">

  <font color="#000000"><strong><font size="+2">value1</font></strong>:</font>
  <font color="#000000">
  <input type="text" name="val1">
    </font></strong></font></label>
    <font color="#000000"><strong><font size="+2">&nbsp;
</font></strong></font></p>
  <p><font color="#000000"><strong><font size="+2">value2:
    <input type="text" name="val2">
    </font></strong></font></p>
  <p> <font color="#000000"><strong><font size="+2">
    <label>value3:</label>
  </font></strong></font><font color="#0000FF"><strong><font
size="+2"><label></label>
  </font></strong></font><strong><font color="#8000FF"
size="+2"><label></label>
    </font> <font size="+2">
    <label></label>
    </font>
    <label></label>
    </strong>
    <label>
    <input type="text" name="val3">
    </label>
    &nbsp; </p>
  <p> <font color="#FF0080" size="+2">
    <input type="submit" name="Submit" value="Send Data">
    </font> </p>
</form>
</body>
</html>

 

//============================================================

save.php

This use to write data to the database and text file

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
echo $va11=$_POST['val1'];
echo $val2=$_POST['val2'];
echo $val3=$_POST['val3'];

$ourFileName = "C:\wamp\www\saveD\outtoc.txt";
$ourFileHandle = fopen($ourFileName,'w') or die("can't open file");
fwrite($ourFileHandle,$va11);
fwrite($ourFileHandle,$val2);
fwrite($ourFileHandle,$val3);
fclose($ourFileHandle);
$date_array = date(h);

$date_array1 = date(i);

$date_array3 = date(A);

$timeU ="$date_array:$date_array1$date_array3";
$dateU="$date_array2:$date_array2";
$connect =mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("db1");
$quary3="insert into table1 values('$va11','$val2','$val3','$timeU')";
$results = mysql_query($quary3) or die(mysql_error());
if ($results==1)
{
print "\n";
echo "\n Insert values Success";
}
?>
</body>
</html>

Wednesday, September 2, 2009

Add certificate to keystore in blackberry mobile device

In blackberry applications when we establish connection with server that asks for
security certificate.To over come this problem we can add certificate and trust the application
using this method.To save certificate within application you can use my early post regarding
the store file within an application to store infomation.
This method add certificate to keystore when it runs

public void addCertToDeviceKeyStore (Certificate certificate)
{
KeyStore keyStore = DeviceKeyStore.getInstance();
//check if certificate is not already in the DeviceKeyStore
if (!keyStore.isMember(certificate))
{
try {
keyStore.set(null,certificate.getSubjectFriendlyName(),certificate,certificate.getStatus(),
keyStore.getTicket());
}
catch (Exception e)
{
\\error message
}
}

Read File in Source Folder (Class) Blackberry Mobile-Can use to keep constant values, Settings and certificates

Sometimes we need to keep some files within our project and use them to keep data.
for this purpose we can use this method.Once we make cod or alx we don't have to
worry about this file or its location.specially store information like top scores in some
game,settings,security certificates we can use this

public String ReadFile()
{
//This retturns the String in FileName.txt
//File must locate in Src Folder
try {
Class classs = Class.forName("packageName.ClassName");
//Source Package neme and Class name
InputStream is = classs.getResourceAsStream("/FileName.txt");
byte[] data = new byte[is.available()];
is.read(data, 0, is.available());
String c =new String(data);
return c;
}
catch (Exception ioe)
{
Dialog.alert("Error");
return null;
}
}

Display WebPage on Top of Application in Blackberry Mobile Device

Sometimes we need to display web page on top of our blackberry application
to display help page or link some web page in such cases we can use this method to
call that web page.That opens given web page on top of application

public void run()
{
//getPage method is also i have mentioned in This Blog
//please refer that
try {
BrowserSession bSession = Browser.getDefaultSession();
byte bytes[] = getPage("www.google.com").getBytes();
//To use this You have download "org/apache/commons/codec"
//and save in src folder
Base64 bb=new Base64();
byte bytes1[]=Base64.encodeBase64(bytes);
String str=new String(bytes1);
bSession.displayPage("data:text/html;base64,"+str);
}
catch (Exception e)
{
Dialog.alert("Error In connecting="+e.toString());
}
}

Read Text File in Blackberry Mobile Device

public String readFile(String path)
{
//File path Should be given like> readFile("file:///SDCard/as.txt")
String str = null;
try
{
FileConnection fc = (FileConnection)Connector.open(path,Connector.READ);
if(!fc.exists())
{
Dialog.alert("File doesn't exist!");
}
else
{
int size = (int)fc.fileSize();
InputStream is = fc.openInputStream();
byte bytes[] = new byte[size];
is.read(bytes, 0, size);
str=new String(bytes);
}

}
catch (IOException ioe)
{
Dialog.alert(ioe.getMessage());
}
return str;
}