J2ME – Bluetooth Chat – Full source code

Posted: March 10, 2012 in Android Posts, Java Posts
Tags: , , , , ,

/*
* BTC.java
*
* Created on March 7, 2008, 11:28 AM
*/

import com.sun.midp.lcdui.Text;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
*
* @author raymond
* @version
*/
public class BTC extends MIDlet {
Displayable d1;
graphics g;
login l=new login();
newuser n=new newuser();
listuser lu=new listuser();
Form f=null;
Display m=null;
Command newuser=new Command(“NEW USER”,Command.EXIT,2);
Command listuser=new Command(“LIST USERS”,Command.EXIT,3);
Command login=new Command(“LOGIN”,Command.EXIT,1);
Command exit=new Command(“EXIT”,Command.EXIT,0);

public void startApp() {

m=Display.getDisplay(this);
g=new graphics();

d1=g;
d1.addCommand(newuser);
d1.addCommand(login);
d1.addCommand(exit);
d1.addCommand(listuser);
m.setCurrent(d1);

d1.setCommandListener(new CommandListener()
{
public void commandAction(Command command, Displayable displayable) {
if(command==exit)
notifyDestroyed();
else if(command==login)
l.display(m);
else if(command==newuser)
n.display(m);
else if(command==listuser)
lu.display(m);

}
}
);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}
}

 ——————

import com.sun.midp.io.j2me.storage.File;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Choice;

import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.UUID;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.L2CAPConnectionNotifier;
import javax.bluetooth.L2CAPConnection;

import javax.bluetooth.BluetoothStateException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

public class ChatController extends MIDlet implements CommandListener
{
private Alert a,a1=null;
private Displayable dis,d2= null;
private Form mainForm = null;
private ChoiceGroup devices = null;

private TextField outTxt = null;
private Command exit = null;
private Command start = null;
private Command connect = null;
private Command send = null;
private Command select = null;
private Command schat=null;
private StringItem status = null;
private StringItem chat = null;
private Display d1;

private LocalDevice local = null;
private RemoteDevice rDevices[];
private ServiceRecord service = null;
private DiscoveryAgent agent = null;
private DiscoveryAgent agentPC = null;

private L2CAPConnectionNotifier notifier;
private L2CAPConnectionNotifier notifierPC;

private L2CAPConnection connection = null;
private L2CAPConnection connectionPC = null;

private static final String UUID_STRING = “112233445566778899AABBCCDDEEFF”;
private static final String UUID_STRING_PC = “112233445566778899AABBCCDDEECF”;

private boolean running = false;
//private static int flag,chatflag=0;
private Command view;

private String s;
private TextField age = null;
private TextField name = null;
private TextField sex = null;
private TextField hobb = null;

private String s1;

private TextField occu = null;
private TextField qual= null;

private String dt=null;
private String dtPC=null;

public ChatController()
{
//super();

}
public void display(final Display d,final String user)
{
dis=d.getCurrent();
s=user;

mainForm = new Form(“CHAT”);
devices = new ChoiceGroup(null,Choice.EXCLUSIVE);
outTxt = new TextField(“outgoing msg:”,””,256,TextField.ANY);
exit = new Command(“EXIT”,Command.EXIT,1);
start = new Command(“START”,Command.SCREEN,2);
connect = new Command(“CONNECT”,Command.SCREEN,2);
send = new Command(“SEND”,Command.SCREEN,2);
select = new Command(“SELECT”,Command.SCREEN,2);
view=new Command(“VIEW PROFILE”,Command.SCREEN,1);
schat=new Command(“START CHAT”,Command.SCREEN,2);
status = new StringItem(“status : “,null);
chat=new StringItem(“\n”,null);

name = new TextField(“Name:”,””,256,TextField.ANY);
age = new TextField(“Age:”,””,256,TextField.ANY);
sex = new TextField(“Sex:”,””,256,TextField.ANY);
hobb = new TextField(“Hobbies:”,””,256,TextField.ANY);
qual = new TextField(“Qualification:”,””,256,TextField.ANY);
occu = new TextField(“Occupation:”,””,256,TextField.ANY);

mainForm.append(status);
mainForm.append(chat);

mainForm.addCommand(exit);
mainForm.setCommandListener(this);

try
{
RecordStore rs2= RecordStore.openRecordStore(“chat”,true);
RecordEnumeration re=null;
re=rs2.enumerateRecords(null,null,false);

while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
System.out.println(str1);
}

rs2.closeRecordStore();
}
catch(Exception e)
{

}

running = true;
mainForm.addCommand(start);
mainForm.addCommand(connect);

try
{
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
agentPC = local.getDiscoveryAgent();

}
catch(BluetoothStateException bse)
{
status.setText(“BluetoothStateException unable to start:”+bse.getMessage());
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{}
notifyDestroyed();
}
d1=d ;
d1.setCurrent(mainForm);
d2=d1.getCurrent();
}

protected void startApp() throws MIDletStateChangeException
{
}

protected void pauseApp()
{
running = false;
releaseResources();
}

protected void destroyApp(boolean uncond) throws MIDletStateChangeException
{
running = false;
releaseResources();
}

public void commandAction(Command cmd,Displayable disp)
{
if(cmd==exit)
{
System.out.println(“inside exit”);
try
{
RecordStore rs=RecordStore.openRecordStore(“chat”,true);
if(!chat.getText().equals(“”))
{

byte []data1=(s+”|\n”+chat.getText()).getBytes();
rs.addRecord(data1,0,data1.length);
Alert a3= new Alert(“”,”SAVED”,null,AlertType.INFO);
d1.setCurrent(a3);
rs.closeRecordStore();
}
}
catch(Exception e)
{

}
running = false;
releaseResources();
d1.setCurrent(dis);
}
else if(cmd==start)
{
new Thread()
{
public void run()
{
startServer();

}
}.start();
}
else if(cmd==connect)
{

status.setText(“searching for devices…”);
mainForm.removeCommand(connect);
mainForm.removeCommand(start);
mainForm.append(devices);

DeviceDiscoverer discoverer = new DeviceDiscoverer(ChatController.this);
try
{
agent.startInquiry(DiscoveryAgent.GIAC,discoverer);
agentPC.startInquiry(DiscoveryAgent.GIAC,discoverer);

}

catch(IllegalArgumentException iae)
{
status.setText(“BluetoothStateException :”+iae.getMessage());
}
catch(NullPointerException npe)
{
status.setText(“BluetoothStateException :”+npe.getMessage());
}
catch(BluetoothStateException bse1)
{
status.setText(“BluetoothStateException :”+bse1.getMessage());
}
}
else if(cmd==select)
{
status.setText(“searching devices for service…”);
int index = devices.getSelectedIndex();

mainForm.removeCommand(select);
mainForm.addCommand(view);
mainForm.addCommand(schat);
ServiceDiscoverer serviceDListener = new ServiceDiscoverer(ChatController.this);
int attrSet[] = {0×0100}; //returns service name attribute
UUID[] uuidSet = {new UUID(UUID_STRING,false)};
ServiceDiscoverer serviceDListenerPC = new ServiceDiscoverer(ChatController.this);
int attrSetPC[] = {0×0100}; //returns service name attribute
UUID[] uuidSetPC = {new UUID(UUID_STRING_PC,false)};

try
{

agentPC.searchServices(attrSetPC,uuidSetPC,rDevices[0],serviceDListener);

agent.searchServices(attrSet,uuidSet,rDevices[index],serviceDListener);
}
catch(IllegalArgumentException iae1)
{
status.setText(“BluetoothStateException :”+iae1.getMessage());
}
catch(NullPointerException npe1)
{
status.setText(“BluetoothStateException :”+npe1.getMessage());
}
catch(BluetoothStateException bse11)
{
status.setText(“BluetoothStateException :”+bse11.getMessage());
}
}
else if(cmd==send)
{
// status.setText(“Connected…”);
new Thread()
{
public void run()
{
sendMessage();
}
}.start();
}

else if(cmd==view)
{
mainForm.delete(mainForm.size()-1);//deletes choiceGroup
mainForm.removeCommand(view);
System.out.println(“View prof…..”);
vprofilercv();
}
else if(cmd==schat)
{
mainForm.removeCommand(schat);
mainForm.removeCommand(view);

mainForm.deleteAll();
mainForm.append(status);
mainForm.append(chat);
s1=s;
System.out.println(“..”+s);

new Thread()
{
public void run()
{
try
{

System.out.println(“Inside thread”);
String message1 = “Hi”;
byte[] data = message1.getBytes();
int transmitMTU = connection.getTransmitMTU();
if(data.length <= transmitMTU)
{
connection.send(data);
}
status.setText(“waiting for connection….”);
String prof=vprofile();
System.out.println(“Profile……..”+prof);
sendMessage(prof);

startReciever();
System.out.println(“startrcvr inside serv search finished”);

}
catch(Exception e1)
{

}
}

}.start();

}
}

//this method is called from DeviceDiscoverer when device inquiry finishes
public void deviceInquiryFinished(RemoteDevice[] rDevices,String message)
{
this.rDevices = rDevices;
String deviceNames[] = new String[rDevices.length];
String PC ;
for(int k=0;k<rDevices.length;k++)
{
try
{
PC =rDevices[0].getFriendlyName(false);

deviceNames[k] = rDevices[k].getFriendlyName(false);
}
catch(IOException ioe)
{
status.setText(“IOException :”+ioe.getMessage());
}
}
for(int l=0;l<deviceNames.length;l++)
{
devices.append(deviceNames[l],null);
}
mainForm.addCommand(select);

status.setText(message);
}

//called by ServiceDiscoverer when service search gets completed
public void serviceSearchFinished(ServiceRecord service,String message)
{
String url = “”;
this.service = service;
status.setText(message);
try
{
url = service.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);
}
catch (IllegalArgumentException iae1)
{}
try
{

connection = (L2CAPConnection)Connector.open(url);
connectionPC = (L2CAPConnection)Connector.open(url);

// sendMessage(prof);
}
catch(IOException ioe1)
{
status.setText(“IOException :”+ioe1.getMessage());
}
}

// this method starts L2CAPConnection chat server from server mode
public void startServer()
{

status.setText(“server starting…”);
mainForm.removeCommand(connect);
mainForm.removeCommand(start);
try
{
local.setDiscoverable(DiscoveryAgent.GIAC);

notifier = (L2CAPConnectionNotifier)Connector.open(“btl2cap://localhost:”+UUID_STRING+”;name=L2CAPChat”);
notifierPC = (L2CAPConnectionNotifier)Connector.open(“btl2cap://localhost:”+UUID_STRING_PC+”;name=L2CAPChat”);

ServiceRecord record = local.getRecord(notifier);
String conURL = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);
status.setText(“server running…”);

dt=vprofile();
System.out.println(dt);
connection = notifier.acceptAndOpen();
connectionPC = notifierPC.acceptAndOpen();

sendMessage(dt);
int receiveMTU = connection.getReceiveMTU();
byte[] data1 = new byte[receiveMTU];
int length = connection.receive(data1);
String message2 = new String(data1,0,length);
if(message2.equals(“Hi”))
{
System.out.println(“INSIDE IF”);
final Command accept=new Command(“Accept”,Command.SCREEN,1);
final Command deny=new Command(“Deny”,Command.SCREEN,2);
final Command vw=new Command(“ViewProfile”,Command.EXIT,1);
a=new Alert(“Alert”,”Remote user wants 2 chat… accept/deny”,null,AlertType.CONFIRMATION);
a.setTimeout(Alert.FOREVER);
a.addCommand(accept);
a.addCommand(deny);
a.addCommand(vw);
d1.setCurrent(a);
a.setCommandListener(new CommandListener(){
public void commandAction(Command c,Displayable d)
{
if(c==accept)
{

new Thread()
{
public void run()
{
d1.setCurrent(mainForm);
System.out.println(“startrcvr inside accept”);
//flag=1;
startReciever();

}
}.start();

}
else if(c==deny)
{

d1.setCurrent(d2);
System.out.println(“startrcvr inside deny”);

try
{
String message1 = “aaa”;
byte[] data = message1.getBytes();
int transmitMTU = connection.getTransmitMTU();
if(data.length <= transmitMTU)
{
connection.send(data);
System.out.println(“deny……..”);

}
new Thread()
{
public void run()
{
d1.setCurrent(d2);
System.out.println(“startrcvr inside deny”);
//flag=1;
startReciever();

}
}.start();

}
catch(Exception e)
{

}
}
else if(c==vw)
{
System.out.println(“insie view…..”);
Form f1=new Form(“profile”);
Command ok=new Command(“OK”,Command.OK,1);
TextField name = new TextField(“Name:”,””,256,TextField.ANY);
TextField age = new TextField(“Age:”,””,256,TextField.ANY);
TextField sex = new TextField(“Sex:”,””,256,TextField.ANY);
TextField hobb = new TextField(“Hobbies:”,””,256,TextField.ANY);
TextField qual = new TextField(“Qualification:”,””,256,TextField.ANY);
TextField occu = new TextField(“Occupation:”,””,256,TextField.ANY);
int index;
f1.append(name);
f1.append(age);
f1.append(sex);
f1.append(hobb);
f1.append(qual);
f1.append(occu);
f1.addCommand(ok);
d1.setCurrent(f1);
try
{
{
System.out.println(“inside view pro…….rcv….”);
int receiveMTU = connection.getReceiveMTU();
byte[] data = new byte[receiveMTU];
int length = connection.receive(data);
String message = new String(data,0,length);
System.out.println(message);
String str1=new String(message);

System.out.println(str1);

// flag=1;
for(int i=0;i<=5;i++)
{
index = str1.indexOf(“|”);
if(i==0)
name.setString(str1.substring(0,index));
else if(i==1)
age.setString(str1.substring(0,index));
else if(i==2)
sex.setString(str1.substring(0,index));
else if(i==3)
hobb.setString(str1.substring(0,index));
else if(i==4)
qual.setString(str1.substring(0,index));
else if(i==5)
occu.setString(str1.substring(0,index));

str1=str1.substring(index+1,str1.length());

}
}
}
catch(Exception e)
{

}
d1.setCurrent(f1);
f1.setCommandListener(new CommandListener(){
public void commandAction(Command c,Displayable d)
{
d1.setCurrent(a);
}
});

}
}
});
}
}

catch(IOException ioe3)
{
status.setText(“IOException :”+ioe3.getMessage());
}
}

//starts a message reciever listening for incomming message
public void startReciever()
{

mainForm.removeCommand(view);

mainForm.addCommand(send);
mainForm.append(outTxt);
while(running)
{
try
{
if(connection.ready())
{

int receiveMTU = connection.getReceiveMTU();
byte[] data = new byte[receiveMTU];
int length = connection.receive(data);
String message = new String(data,0,length);
System.out.println(message);

if(message.equals(“aaa”))
{

System.out.println(“denied……………..INSIDE IF”);
a1=new Alert(“Denied”,”Has denied the request for chat”,null,AlertType.INFO);
a1.setTimeout(Alert.FOREVER);
d1.setCurrent(a1);
a1.setCommandListener(new CommandListener(){
public void commandAction(Command c,Displayable d)
{
d1.setCurrent(d2);
releaseResources();
}
});
}
else
{
int l=message.lastIndexOf(‘|’);
System.out.println(“………”+l);
if(l!=-1)
chat.setText(“”);

else
{
if(chat.getText()!=null)
chat.setText(chat.getText()+”\n”+ message);
else
chat.setText(message);

status.setText(“Connected……”);
}
}
}
}
catch(IOException ioe4)
{
status.setText(“IOException :”+ioe4.getMessage());
}

}

}
//sends a message over L2CAP
public void sendMessage()
{
try
{
if(chat.getText()!=null)
chat.setText(chat.getText()+”\n”+s+”:”+outTxt.getString());
else
chat.setText(s+”:”+outTxt.getString());
String message = s+”:”+outTxt.getString();
outTxt.setString(“”);
byte[] data = message.getBytes();
int transmitMTU = connection.getTransmitMTU();
if(data.length <= transmitMTU)
{
connection.send(data);
connectionPC.send(data);
}
else
{
status.setText(“message ….”);
}
}
catch (IOException ioe5)
{
status.setText(“IOException :”+ioe5.getMessage());
}
}
public void sendMessage(String msg)
{
try
{
//System.out.println(msg);

String message =msg;
File fr = new File() ;//new FileWriter(“c:/a.csv”);

byte[] data = message.getBytes();
int transmitMTU = connection.getTransmitMTU();
if(data.length <= transmitMTU)
{
connection.send(data);
connectionPC.send(data);

}
else
{
status.setText(“message ….”);
}
}
catch (IOException ioe5)
{
status.setText(“IOException :”+ioe5.getMessage());
}
}

//closes L2CAP connection
public void releaseResources()
{
try
{

if(connection != null)
connection.close();
System.out.println(“conn close”);
if(notifier != null)
notifier.close();
System.out.println(“notifier close”);
}
catch(IOException ioe6)
{
status.setText(“IOException :”+ioe6.getMessage());
}
}

public String vprofile()
{
int index;
String dat = null;
try
{
System.out.println(s);
RecordStore rs= RecordStore.openRecordStore(“btc5″,true);
RecordEnumeration re=null;
re=rs.enumerateRecords(null,null,false);
while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
index = str1.indexOf(“|”);
String s1=str1.substring(0,index);
str1=str1.substring(index+1,str1.length());
if(s1.equals(s))
{
System.out.println(“readyyyy”);

dat=str1;

}

}
rs.closeRecordStore();
}
catch(Exception e)
{

}

return(dat);

}

private void vprofilercv() {
int index;
mainForm.append(name);
mainForm.append(age);
mainForm.append(sex);
mainForm.append(hobb);
mainForm.append(qual);
mainForm.append(occu);
try
{
{
String message=null ;
System.out.println(“inside view pro…….rcv….”);
int receiveMTU = connection.getReceiveMTU();
byte[] data = new byte[receiveMTU];
int length = connection.receive(data);
message = new String(data,0,length);
System.out.println(message);
String str1=new String(message);
System.out.println(str1);
if(message!=null)
{
for(int i=0;i<=5;i++)
{
index = str1.indexOf(“|”);
if(i==0)
name.setString(str1.substring(0,index));
else if(i==1)
age.setString(str1.substring(0,index));
else if(i==2)
sex.setString(str1.substring(0,index));
else if(i==3)
hobb.setString(str1.substring(0,index));
else if(i==4)
qual.setString(str1.substring(0,index));
else if(i==5)
occu.setString(str1.substring(0,index));

str1=str1.substring(index+1,str1.length());

}
}
else
{
name.setString(“”);
age.setString(“”);
sex.setString(“”);
hobb.setString(“”);
qual.setString(“”);
occu.setString(“”);
}
}
}
catch(Exception e)
{

}
return;
}
}

—————

import java.util.Vector;

import javax.bluetooth.RemoteDevice;
import javax.bluetooth.DeviceClass;

import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.ServiceRecord;

public class DeviceDiscoverer implements DiscoveryListener
{
private ChatController controller = null;
private Vector devices = null;
private RemoteDevice[] rDevices = null;

public DeviceDiscoverer(ChatController controller)
{
super();
this.controller = controller;
devices = new Vector();
}

public void deviceDiscovered(RemoteDevice remote,DeviceClass dClass)
{
devices.addElement(remote);
}

public void inquiryCompleted(int descType)
{
String message = “”;

switch(descType)
{
case DiscoveryListener.INQUIRY_COMPLETED:
message = “INQUIRY_COMPLETED”;
break;
case DiscoveryListener.INQUIRY_TERMINATED:
message = “INQUIRY_TERMINATED”;
break;
case DiscoveryListener.INQUIRY_ERROR:
message = “INQUIRY_ERROR”;
break;
}

rDevices = new RemoteDevice[devices.size()];
for(int i=0;i<devices.size();i++)
rDevices[i] = (RemoteDevice)devices.elementAt(i);

controller.deviceInquiryFinished(rDevices,message);//call of a method from ChatController class
devices.removeAllElements();

controller = null;
devices = null;
}

public void servicesDiscovered(int transId,ServiceRecord[] services)
{}

public void serviceSearchCompleted(int transId,int respCode)
{}

}

——————-

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Graphics;
import java.io.*;
/*
* graphics.java
*
* Created on March 7, 2008, 11:38 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

/**
*
* @author raymond
*/
public class graphics extends Canvas{

/** Creates a new instance of graphics */
public graphics() {
}

public void paint(Graphics g) {
int h=getHeight();
int w=getWidth();
g.setColor(0×000000);
g.fillRect(0,0,w,h);

g.drawImage(LoadImage(“/btc1.JPG”),w/2+10,h+40, Graphics.BOTTOM | Graphics.HCENTER);

}

private Image LoadImage(String st) {
Image img=null;
try
{
img=Image.createImage(st);

}
catch(Exception e)
{
System.out.println(e);

}
return img;

}

}

——————-

import javax.microedition.lcdui.*;
/*
* help.java
*
* Created on March 7, 2008, 3:17 PM
*
*/

/**
*
* @author raymond
*/
public class help {
Displayable d1;
Displayable d2=null;
Command back=new Command (“BACK”,Command.SCREEN,0);
StringItem help;

/** Creates a new instance of help */
public help() {
}
public void display1(final Display d)
{
d2=d.getCurrent();
Form f=new Form(“Help”);

help=new StringItem(“Use LOOK FOR FRIENDS to find friends around.\nYou can create private Chat sessions by selecting one of the devices listed.\n\tVIEW PROFILE can be used to identify the user on the selected remote device.\n\tSTARTCHAT is used to begin the chat session\n\nMY PROFILE is for setting your profiles which will be viewed by friends.\n\nCHAT HISTORY can be used for viewing the previous chats of the logged in user..”,null);
// d1=d.getCurrent();
//d1.addCommand(back);
//d1.
f.append(help);
f.addCommand(back);
d.setCurrent(f);
f.setCommandListener(new CommandListener()
{
public void commandAction(Command c,Displayable di)
{
d.setCurrent(d2);
}
});
}
}

——————

/*
* listuser.java
*
* Created on March 29, 2008, 11:21 PM
*
*/

/**
*
* @author Administrator
*/
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import java.io.*;

public class listuser extends MIDlet{

Displayable d1=null;
int flag=0,i,index;
RecordEnumeration re=null;
RecordStore rs=null;
Command next=new Command(“NEXT”,Command.SCREEN,0);
Command cancel=new Command(“CANCEL”,Command.EXIT,0);
TextField user,email,phone,addr;
/** Creates a new instance of listuser */
public listuser() {
}
public void display(final Display d)
{
d1=d.getCurrent();
Form f=new Form(“Users”);
user=new TextField(“USERNAME”,””,32,TextField.ANY);
email=new TextField(“E-MAIL”,””,32,TextField.ANY);
phone=new TextField(“PHONE NO”,””,32,TextField.ANY);
addr=new TextField(“ADDRESS”,””,32,TextField.ANY);
f.append(user);
f.append(email);
f.append(phone);
f.append(addr);
f.addCommand(next);
f.addCommand(cancel);
try {
rs= RecordStore.openRecordStore(“btc”,true);

re=rs.enumerateRecords(null,null,false);
}
catch (RecordStoreException ex) {
ex.printStackTrace();
}

f.setCommandListener(new CommandListener()
{
public void commandAction(Command c,Displayable di)
{

if(c==next)
{

try
{

if(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
for(i=0;i<5;i++)
{
index = str1.indexOf(“|”);
if(i==0)
user.setString(str1.substring(0,index));
else if(i==1)
{

}
else if(i==2)
email.setString(str1.substring(0,index));
else if(i==3)
phone.setString(str1.substring(0,index));
else if(i==4)
addr.setString(str1.substring(0,index));

str1=str1.substring(index+1,str1.length());
}

}
else
{
Alert a1= new Alert(“ALERT”,” no more users.. “,null,AlertType.INFO);
d.setCurrent(a1);
rs.closeRecordStore();
rs=RecordStore.openRecordStore(“btc”,true);
}
}
catch(Exception e)
{

}
}
else if(c==cancel)
{
d.setCurrent(d1);
}
}
});
d.setCurrent(f);
}

protected void startApp() throws MIDletStateChangeException {
}

protected void pauseApp() {
}

protected void destroyApp(boolean b) throws MIDletStateChangeException {
}
}

——————–

/*
* login.java
*
* Created on February 9, 2008, 10:45 AM
*/

//package chat;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;

/**
*
* @author Administrator
* @version
*/
public class login extends MIDlet
{
TextField user,pass;
Displayable d1=null;
menu mn=new menu();
Command ok=new Command(“OK”,Command.OK,0);
Command back=new Command(“BACK”,Command.BACK,0);
public void startApp()
{

}

public void pauseApp()
{

}
public void destroyApp(boolean unconditional)
{
}

public void display(final Display d) {
d1=d.getCurrent();
Form f= new Form(“LOGIN”);
user=new TextField(“USERNAME”,””,32,TextField.ANY);
pass=new TextField(“PASSWORD”,””,32,TextField.PASSWORD);
f.append(user);
f.append(pass);
f.addCommand(ok);
f.addCommand(back);
f.setCommandListener(new CommandListener(){
public void commandAction(Command c,Displayable s)
{
if(c==ok)
{
String Uname=user.getString();
String Pword=pass.getString();
RecordStore rs=null;
int count=0,flag=0;
try
{

rs= RecordStore.openRecordStore(“btc”,true);
RecordEnumeration re=null;
re=rs.enumerateRecords(null,null,false);
while(re.hasNextElement())
{
count++;
byte []data=re.nextRecord();
String str1=new String(data);
int index = str1.indexOf(“|”);
String s1=str1.substring(0,index);
str1=str1.substring(index+1,str1.length());
index = str1.indexOf(“|”);
String s2=str1.substring(0,index);

if(s1.equals(Uname))
{
flag=1;
if(s2.equals(Pword))
{
// Alert a3= new Alert(“LOGGED IN”,” YOU HAVE SUCCESSFULLY LOGGED IN!!!!!!!”,null,AlertType.INFO);
// d.setCurrent(a3);
String u=user.getString();

user.setString(“”);
pass.setString(“”);
mn.display1(d,u);
}
else
{
Alert a2= new Alert(“ALERT”,” WRONG PASSWORD”,null,AlertType.INFO);
d.setCurrent(a2);
}
}

}

if(flag==0)
{
Alert a1= new Alert(“ALERT”,” USERNAME DONOT EXISTS”,null,AlertType.INFO);

d.setCurrent(a1);
}
rs.closeRecordStore();
}
catch(Exception e)
{
e.printStackTrace();
}

}
else if(c==back)
d.setCurrent(d1);
}

});
d.setCurrent(f);
}
}

————————

/*
* lookforfriends.java
*
* Created on April 14, 2008, 4:52 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

/**
*
* @author Administrator
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;
import java.util.*;
import java.io.*;
public class lookforfriends extends MIDlet implements CommandListener,Runnable,DiscoveryListener{

private Command discover,exit,select;
LocalDevice local;
private DiscoveryAgent discoveryagent;
private Hashtable bluetoothdevices=new Hashtable();
List devicelist;
Displayable d1;
private Display dis;
/** Creates a new instance of lookforfriends */
public lookforfriends() {
}
public void display(final Display d)
{
d1=d.getCurrent();
discover=new Command(“Discover”,Command.SCREEN,0);
exit=new Command(“Exit”,Command.EXIT,0);
select=new Command(“Select”,Command.OK,0);
devicelist=new List(“Select device”,List.IMPLICIT);
devicelist.addCommand(exit);
devicelist.setCommandListener(new CommandListener(){
public void commandAction(Command command, Displayable displayable) {
if(command==exit)
{
d.setCurrent(d1);
}
}
}
);
Form f=new Form(“Devices”);
f.addCommand(discover);
f.addCommand(exit);
f.setCommandListener(new CommandListener(){
public void commandAction(Command command, Displayable displayable) {
if(command==exit)
{
d.setCurrent(d1);
}
if(command==discover)
{
doBluetoothDiscovery();

}
}
});
d.setCurrent(f);
dis=d;
}
private void doBluetoothDiscovery()
{
printString(“doBluetoothdisc”);
Thread t=new Thread(this);
t.start();
// bluetoothDiscovery(d);
}
public void printString(String s)
{
System.out.println(s);
}
private void bluetoothDiscovery()
{
printString(“Bluetooth!!!!!!!!!!!!”);
LocalDevice localdevice;
try
{
localdevice=LocalDevice.getLocalDevice();
}
catch(BluetoothStateException e)
{
printString(“BluetoothStateException:”+e);
return;
}
discoveryagent=localdevice.getDiscoveryAgent();
RemoteDevice devices[];
try
{
devices=discoveryagent.retrieveDevices(DiscoveryAgent.CACHED);
if(devices!=null)
{
for(int i=0;i<devices.length;i++)
{
bluetoothdevices.put(devices[i].getFriendlyName(false),devices[i]);
printString(“Device(cached):”+devices[i].getFriendlyName(false)+””+devices[i].getBluetoothAddress());
}

}
devices=discoveryagent.retrieveDevices(DiscoveryAgent.PREKNOWN);
if(devices!=null)
{
for(int i=0;i<devices.length;i++)
{
bluetoothdevices.put(devices[i].getFriendlyName(false),devices[i]);
printString(“Device(cached):”+devices[i].getFriendlyName(false)+””+devices[i].getBluetoothAddress());
}

}

}
catch(IOException e)
{
printString(“Exception(b2):”+e);
}
try
{
discoveryagent.startInquiry(DiscoveryAgent.GIAC,this);

}
catch(BluetoothStateException e)
{
printString(“Exception(b3):”+e);
}
printString(“Return from bluetoothDiscovery()”);

}

protected void startApp() throws MIDletStateChangeException {
}

protected void pauseApp() {
}

protected void destroyApp(boolean b) throws MIDletStateChangeException {
}
private void bluetoothCopyDeviceTableToList()
{
printString(“Bluetoothcopy!!!!!!”);
//Remove old entries
for(int i=devicelist.size();i>0;i–)
{
devicelist.delete(i-1);
}
//append keys from table
for(Enumeration e=bluetoothdevices.keys();e.hasMoreElements();)
{
try
{
String name=(String)e.nextElement();
devicelist.append(name,null);
}
catch(Exception e1)
{

}
}
dis.setCurrent(devicelist);
}

public void run() {
printString(“Bluetoothrun!!!”);
bluetoothDiscovery();
}

public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
try
{
if(!remoteDevice.getFriendlyName(false).equals(“PC”))
printString(“Devicediscovered:”+remoteDevice.getFriendlyName(false));
//add device to table
bluetoothdevices.put(remoteDevice.getFriendlyName(false),remoteDevice);
}
catch(Exception e2)
{
printString(“Exception(b4):”+e2);
}
}

public void servicesDiscovered(int i, ServiceRecord[] serviceRecord) {
}

public void serviceSearchCompleted(int i, int i0) {
}

public void commandAction(Command command, Displayable displayable) {
}
public void inquiryCompleted(int i) {
printString(“Inquiry Completed!!”+i);
bluetoothCopyDeviceTableToList();
}

}

——————————

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import java.io.*;
/*
* menu.java
*
* Created on March 7, 2008, 2:06 PM
*
*/

/**
*
* @author raymond
*/
public class menu extends MIDlet {

//lookforfriends l=new lookforfriends();
ChatController l=new ChatController();
help h=new help();
profile p=new profile();

chathistory ch=new chathistory();

Command help=new Command (“HELP”,Command.EXIT,0);
String []selements ={“Look for Friends”,”Chat History”,”My Profile”,”LOGOUT”};

Displayable d1=null;
List s =new List(“LIST”,List.IMPLICIT,selements,null);

/** Creates a new instance of menu */
public menu() {
}

protected void startApp() throws MIDletStateChangeException {

}
public void display1(final Display d,final String user)
{
d1=d.getCurrent();
s.addCommand(help);
s.setCommandListener(new CommandListener()
{
public void commandAction(Command command, Displayable displayable) {

if(command==help)
{
h.display1(d) ;
}
else
{
String str=s.getString(s.getSelectedIndex());
System.out.println(str);
if(str.equals(“Look for Friends”))
{
l.display(d,user);
}
else if(str.equals(“Chat History”))
{
ch.display(d,user);
}
else if(str.equals(“My Profile”))
{
p.display(d,user);
}
else if(str.equals(“LOGOUT”))
{
d.setCurrent(d1);
}
}

}
});
d.setCurrent(s);
}
protected void pauseApp() {
}

protected void destroyApp(boolean b) throws MIDletStateChangeException {
}

}

————————-

/*

* newuser.java

*

* Created on February 9, 2008, 9:46 AM

*

*/

package chat;

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import javax.microedition.rms.*;

/**

*

* @author raymond

* @version

*/

public class newuser extends MIDlet

{ // int flag=0,l=0;

Displayable d1=null;

TextField user,pass,retype,email,address,phone;

Command ok=new Command(“OK”,Command.OK,0);

Command back=new Command(“BACK”,Command.BACK,0);

public void display(final Display d)

{

d1=d.getCurrent() ;

Form f= new Form(“NEWUSER”);

user=new TextField(“USERNAME”,””,32,TextField.ANY);

pass=new TextField(“PASSWORD”,””,32,TextField.PASSWORD);

retype=new TextField(“RETYPE PASSWORD”,””,32,TextField.PASSWORD);

email=new TextField(“EMAIL”,””,32,TextField.ANY);

address=new TextField(“ADDRESS”,””,32,TextField.ANY);

phone=new TextField(“PHONE NO”,””,32,TextField.NUMERIC);

f.append(user);

f.append(pass);

f.append(retype);

f.append(email);

f.append(phone);

f.append(address);

f.addCommand(ok);

f.addCommand(back);

f.setCommandListener(new CommandListener()

{

public void commandAction(Command c,Displayable s)

{

int flag=0;

if(c==ok)

{

String uname=user.getString();

String pword=pass.getString();

String ret=retype.getString();

String str =uname+”|”+pword;

if(!pword.equals(ret))

{

Alert a1= new Alert(“ALERT”,”PASSWORD ENTRIES DOESNT MATCH”,null,AlertType.INFO);

d.setCurrent(a1);

}

else

{

// flag=0;

try

{

RecordStore rs= RecordStore.openRecordStore(“btc”,true);

RecordEnumeration re=null;

re=rs.enumerateRecords(null,null,false);

while(re.hasNextElement())

{

byte []data=re.nextRecord();

String str1=new String(data);

int index = str1.indexOf(“|”);

String s1=str1.substring(0,index);

System.out.println(s1+” “+uname);

if(s1.equals(uname))

{

flag=1;

Alert a2= new Alert(“ALERT”,”USERNAME EXISTS”,null,AlertType.INFO);

d.setCurrent(a2);

return;

}

}

if(flag==0)

{

try

{

String em=email.getString();

String addr=address.getString();

String phno=phone.getString();

if(!em.equals(“”)&&!addr.equals(“”)&&!phno.equals(“”))

{

str=str+”|”+em+”|”+phno+”|”+addr+”|”;

byte []data1=str.getBytes();

RecordStore rs1= RecordStore.openRecordStore(“btc”,true);

rs1.addRecord(data1,0,data1.length);

Alert a3= new Alert(“ALERT”,”REGISTERED”,null,AlertType.INFO);

d.setCurrent(a3);

user.setString(“”);

pass.setString(“”);

retype.setString(“”);

email.setString(“”);

address.setString(“”);

phone.setString(“”);

}

else

{

Alert a4= new Alert(” ALERT”,”The fields cannot be left

blank..”,null,AlertType.INFO);

d.setCurrent(a4);

}

}

catch(Exception e)

{

System.out.println(e);

}

}

rs.closeRecordStore();

}

catch(Exception e)

{

System.out.println(e);

}

}

}

else if(c==back)

{

d.setCurrent(d1);

}

}

});

d.setCurrent(f);

}

public void startApp()

{

}

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {

}

}

———————–

/*
* profile.java
*
* Created on March 14, 2008, 1:04 PM
*/

/**
*
* @author raymond
*/
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import java.io.*;

public class profile extends MIDlet{

Displayable d1=null;
int flag=0,i,index;
// byte[]dat;

Command save=new Command(“SAVE”,Command.SCREEN,0);

TextField id,name,age,sex,hobb,qual,occu;
Command cancel=new Command(“CANCEL”,Command.EXIT,0);
/** Creates a new instance of profile */
public profile() {
}
public void display(final Display d,final String u)
{
d1=d.getCurrent();
Form f=new Form(“Profile”);
id=new TextField(“Loginid: “,””,32,TextField.ANY);
name=new TextField(“Name: “,””,32,TextField.ANY);
age=new TextField(“Age: “,””,32,TextField.NUMERIC);
sex=new TextField(“Sex: “,””,32,TextField.ANY);
hobb=new TextField(“Hobbies: “,””,100,TextField.ANY);
qual=new TextField(“Qualification: “,””,100,TextField.ANY);
occu=new TextField(“Occupation: “,””,100,TextField.ANY);
f.append(id);
f.append(name);
f.append(age);
f.append(sex);
f.append(hobb);
f.append(qual);
f.append(occu);
f.addCommand(save);
f.addCommand(cancel);
id.setString(u);
try
{
RecordStore rs2= RecordStore.openRecordStore(“btc5″,true);
RecordEnumeration re=null;
re=rs2.enumerateRecords(null,null,false);
System.out.println(“inside btc………”);
while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
System.out.println(str1);
}
rs2.closeRecordStore();
}
catch(Exception e)
{

}
String s=id.getString();
System.out.println(s);
RecordStore rs=null;
try
{
rs= RecordStore.openRecordStore(“btc5″,true);
RecordEnumeration re=null;
re=rs.enumerateRecords(null,null,false);
while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
index = str1.indexOf(“|”);
String s1=str1.substring(0,index);
str1=str1.substring(index+1,str1.length());
if(s1.equals(s))
{

flag=1;
for(i=0;i<=5;i++)
{
index = str1.indexOf(“|”);
if(i==0)
name.setString(str1.substring(0,index));
else if(i==1)
age.setString(str1.substring(0,index));
else if(i==2)
sex.setString(str1.substring(0,index));
else if(i==3)
hobb.setString(str1.substring(0,index));
else if(i==4)
qual.setString(str1.substring(0,index));
else if(i==5)
occu.setString(str1.substring(0,index));

str1=str1.substring(index+1,str1.length());

}

}

}
rs.closeRecordStore();
}
catch(Exception e)
{

}

f.setCommandListener(new CommandListener()
{
public void commandAction(Command c,Displayable di)
{
if(c==save)
{

String s=id.getString();
String na=name.getString();
String ag=age.getString();
String se=sex.getString();
String ho=hobb.getString();
String qu=qual.getString();
String oc=occu.getString();
RecordStore rs=null;
try
{
rs= RecordStore.openRecordStore(“btc5″,true);

RecordEnumeration re=null;

re=rs.enumerateRecords(null,null,false);

if(re.numRecords()==0)
{
System.out.println(“No record”);

if(!na.equals(“”)&&!ag.equals(“”)&&!se.equals(“”)&&!ho.equals(“”)&&!qu.equals(“”)&&!oc.equals(“”))
{
s=s+”|”+na+”|”+ag+”|”+se+”|”+ho+”|”+qu+”|”+oc+”|”;
byte []data1=s.getBytes();
rs.addRecord(data1,0,data1.length);
Alert a3= new Alert(“”,”SAVED”,null,AlertType.INFO);
d.setCurrent(a3);
rs.closeRecordStore();
}
}
while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
index = str1.indexOf(“|”);
String s1=str1.substring(0,index);
if(s1.equals(s))
{
int n=rs.getNextRecordID();
System.out.println(n);
rs.deleteRecord(n-1);

if(!na.equals(“”)&&!ag.equals(“”)&&!se.equals(“”)&&!ho.equals(“”)&&!qu.equals(“”)&&!oc.equals(“”))
{
s1=s1+”|”+na+”|”+ag+”|”+se+”|”+ho+”|”+qu+”|”+oc+”|”;
byte []data1=s1.getBytes();
rs.addRecord(data1,0,data1.length);
Alert a3= new Alert(“”,”SAVED”,null,AlertType.INFO);
d.setCurrent(a3);
rs.closeRecordStore();
}

}
else
{

if(!na.equals(“”)&&!ag.equals(“”)&&!se.equals(“”)&&!ho.equals(“”)&&!qu.equals(“”)&&!oc.equals(“”))
{
s=s+”|”+na+”|”+ag+”|”+se+”|”+ho+”|”+qu+”|”+oc+”|”;
byte []data1=s.getBytes();
rs.addRecord(data1,0,data1.length);
Alert a3= new Alert(“”,”SAVED”,null,AlertType.INFO);
d.setCurrent(a3);
rs.closeRecordStore();
}

}

}
}

catch(Exception e)
{
e.printStackTrace();
}

}
else if(c==cancel)
{
d.setCurrent(d1);
}
}
});
d.setCurrent(f);
}
protected void startApp() throws MIDletStateChangeException {

}

protected void pauseApp() {
}

protected void destroyApp(boolean b) throws MIDletStateChangeException {
}

}

Advertisements
Comments
  1. film izle says:

    Great a person web site manager results weblog post good sharings in this website often have fun

    Like

  2. fans for you and me says:

    very nice post, i certainly love this fabulous website, keep on it

    Like

  3. Emmaline Banos says:

    Thanks a lot for that post. Truly thanks! Really great.

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s