11 Replies - 3031 Views - Last Post: 27 May 2010 - 07:26 PM

#1 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

how to view My Document files in mobile using bluetooth client server

Posted 23 May 2010 - 07:26 PM

my code here is to access My Document files..

import java.io.File;

public class ReadFileName {

public static void main(String[] args) {

File folder = new File('c:/'); // put you my document location here like c:/document and setting/......etc

File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println('File ' + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println('Directory ' + listOfFiles[i].getName());
}
}
}
} 


but i don't know how to convert it to an array to byte so that i can show the files of My document in my mobile using bluetooth..

Is This A Good Question/Topic? 0
  • +

Replies To: how to view My Document files in mobile using bluetooth client server

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10595
  • View blog
  • Posts: 39,236
  • Joined: 27-December 08

Re: how to view My Document files in mobile using bluetooth client server

Posted 23 May 2010 - 09:37 PM

Please work on your code indentations. :) It really isn't easy to read.

You can use the String getBytes() method, which returns a byte[]. You can do this to send the File name to your mobile device. Since mobile devices don't have a lot of memory, I'm guessing you just want to send the name of the Files, and not the contents of the Files.
Was This Post Helpful? 0
  • +
  • -

#3 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

Re: how to view My Document files in mobile using bluetooth client server

Posted 23 May 2010 - 11:18 PM

im sorry..

yes your right. i just want the name of the file to display on the mobile.
and the content will be send if the user request to copy, and it will be save in memory card of the phone.

if the byte is being sent to the phone what will be the code that will accept and display the file names on the mobile?
Was This Post Helpful? 0
  • +
  • -

#4 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

Re: how to view My Document files in mobile using bluetooth client server

Posted 24 May 2010 - 12:37 AM

hmmm..can you help me on how to put it on a getbyte[] method?
Was This Post Helpful? 0
  • +
  • -

#5 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

Re: how to view My Document files in mobile using bluetooth client server

Posted 24 May 2010 - 07:26 PM

and how to accept the byte that the server send to mobile.. how mobile display the names
Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10595
  • View blog
  • Posts: 39,236
  • Joined: 27-December 08

Re: how to view My Document files in mobile using bluetooth client server

Posted 24 May 2010 - 07:34 PM

Take a look at the String class for reading the byte[] into a String.

Quote

if the byte is being sent to the phone what will be the code that will accept and display the file names on the mobile?

I think the Sun Documentation for Bluetooth and J2ME is a great place to start. Note that we do have a policy in which we need to see a good faith effort before we can help you much more. We don't just give out the code. :)

And since this is turning into a Mobile Development question, I'll move this the Mobile Development forum. I also noticed you have a similar thread in the Python forum. Is that relevant to this thread?

Also, for the basics of Mobile Applications in J2ME, check out my tutorial on J2ME- Lifecycle of a MIDlet.

This post has been edited by macosxnerd101: 24 May 2010 - 07:36 PM

Was This Post Helpful? 0
  • +
  • -

#7 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

Re: how to view My Document files in mobile using bluetooth client server

Posted 24 May 2010 - 08:23 PM

yes its relevant..its OK..i know your just here to help and give some info..

i create the program into two languages, but its the same. i don't know how to access My Document files and display it on mobile..i just want to see if which is much easier to access My Document files..
Was This Post Helpful? 1
  • +
  • -

#8 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

Re: how to view My Document files in mobile using bluetooth client server

Posted 24 May 2010 - 09:12 PM

Just the same, i already created my client and server..but all it do is connect and nothing more.i created it in netbeans ide..the problem it that is that i can't view the file of My Documents in my mobile.

Just the same, i already created my client and server..but all it do is connect and nothing more.i created it in netbeans ide..the problem it that is that i can't view the file of My Documents in my mobile.

Just the same, i already created my client and server..but all it do is connect and nothing more.i created it in netbeans ide..the problem it that is that i can't view the file of My Documents in my mobile.
Was This Post Helpful? 0
  • +
  • -

#9 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10595
  • View blog
  • Posts: 39,236
  • Joined: 27-December 08

Re: how to view My Document files in mobile using bluetooth client server

Posted 24 May 2010 - 09:23 PM

Look- we're not going to hand you the code. If you have written all this yourself, then you won't mind showing us your good faith efforts at connecting to the Server and transferring data. Can you also specifically describe your error(s) or problem(s)? Where in the transfer are you having trouble? Do you get Exceptions or Errors? If you are unsure of how to transfer data via bluetooth, the Sun Documentation provides an excellent starting point.
Was This Post Helpful? 0
  • +
  • -

#10 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

Re: how to view My Document files in mobile using bluetooth client server

Posted 25 May 2010 - 10:15 PM

this the client code..

import javax.microedition.lcdui.*;
import javax.bluetooth.*;
import javax.microedition.io.file.*;

import java.util.Hashtable;
import java.util.Vector;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.obex.*;
import java.io.*;
public class ThesisClient implements DiscoveryListener, Runnable  {
   private MobileFileCopier gui;
    public Image bt_logo;
    LocalDevice localDevice;
  private String Filename;
    private DiscoveryAgent discoveryAgent;
    //Collects the remote devices found during a search.
HeaderSet hdr;
    private Vector /* RemoteDevice */ devices = new Vector();
    // Collects the services found during a search.
    private Vector /* ServiceRecord */ records = new Vector();

    // RFCOMM UUID
    private UUID[] uuid = new UUID[2];
    private static final UUID MCFC_SERVER_UUID = new UUID("F0E0D0C0B0A000908070605040302010", false);
    private int[] attrSet = new int[1];
    //
    private int[] searchIDs;

    //ALERT CODES
    private int ALERT_NO_DEVICE_FOUND = 1;
    private int DISCONNECTED = 2;

    Hashtable hashDevices = new Hashtable();

    private Thread clientThread;

    private ClientConnector connector;

    String connectionURL;
    StreamConnection conn;
    DataOutputStream dataout;
   
    private boolean isInitialized;

    ScreenshotHandler scrHandler;

public ThesisClient(MobileFileCopier gui) {
        this.gui = gui;

        try {
            localDevice = LocalDevice.getLocalDevice();
        } catch (BluetoothStateException bse) {
            System.out.println(bse);
        }

        uuid[1] = MCFC_SERVER_UUID;
        uuid[0] = new UUID(0x1101);
     
        clientThread = new Thread(this);
        clientThread.start();

        isInitialized = false;

    }

    public void run() {
        BTconnect();
    }

    void BTconnect() {
        // initialize bluetooth first
        boolean isBTReady = false;
          System.out.println("Bluetooth Device Search starting...");
        try {
        
            discoveryAgent  = LocalDevice.getLocalDevice().getDiscoveryAgent();
            // remember we've reached this point.
            isBTReady = true;
        } catch (Exception e) {
            System.err.println("Can't initialize bluetooth: " + e);
          
        }
       
        if (!isBTReady) {
            return;
        }

        searchBTDevices();

    }

    public void searchBTDevices() {
       

        try {
             devices.removeAllElements();
             localDevice = LocalDevice.getLocalDevice();
       discoveryAgent = localDevice.getDiscoveryAgent();
      // start discovery of new devices
      discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);

        } catch (BluetoothStateException e) {
            System.err.println("Can't start inquiry now: " + e);
        }
    }

    // returns the number of devices found

      private void searchBTServices() {
        records.removeAllElements();
        int i, s;


        searchIDs = new int[devices.size()];

         System.out.println("Services Search started");

        s = devices.size();

        for (i=0; i<s; i++) {
                RemoteDevice rd = (RemoteDevice) devices.elementAt(i);
                try {
                    searchIDs[i] = discoveryAgent.searchServices(null, uuid, rd, this);
                    // Display progress message
                     System.out.println("Service Search in Progress ("+searchIDs+")");
                } catch (BluetoothStateException bse) {

                    System.err.println("Service Search Failed" + bse);
                    return;
                }
            }
    }

    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {

        try
        {
            devices.addElement(btDevice);
            bt_logo = Image.createImage("/4.png");
            String devName = btDevice.getFriendlyName(false);
            if(devName == null || devName.compareTo("") == 0)
            {
                devName = btDevice.getBluetoothAddress();
            }
             Display.getDisplay(gui).setCurrent(gui.getBTDevices_listSCRN());
            gui.getBTDevices_listSCRN().append(devName, bt_logo);
        }
        catch(IOException e) { }

    }
    public void servicesDiscovered(int searchIDs, ServiceRecord[] servRecord) {
       for (int i = 0; i < servRecord.length; i++) {
             System.out.println("A matching device has been found!\n");
            records.addElement(servRecord[i]);
        try {
                 hashDevices.put(servRecord[i].getHostDevice().getFriendlyName(true), servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false));
            } catch (Exception e) {
                 System.out.println("Error" + e);
            }
                System.out.println("with URL:"+servRecord[i].getConnectionURL(1, false).toString()+" \n\n");
            try {
          
                 connectionURL = servRecord[i].getConnectionURL(0,false);
            } catch (Exception e){
                 System.err.println("\n[client:] oops");
            }
 }
    }

 public void inquiryCompleted(int Param) {

    System.out.println("FINISHED SEARCHING FOR DEVICES...\n");
        if (!devices.isEmpty()) {
            for (int i=0;i<devices.size();i++) {
                RemoteDevice rd = (RemoteDevice) devices.elementAt(i);
                try {
                    gui.getStringItem().setText(rd.getFriendlyName(true));
                   
                } catch (IOException ie) {
 }
            }
            searchBTServices();
        }
        if (devices.isEmpty()) {
             System.out.println("No devices has been found.Search Again.\n");
        }
   }
 public void serviceSearchCompleted(int transID, int responseCode) {
        // Now that the service discovery has been completed,
if (records.isEmpty())  {
    System.out.println("No devices with correct service has been found.Search Again.\n");
  
    }
       else {
        Display.getDisplay(gui).setCurrent(gui.getBTDevices_listSCRN());
    }
 }
     
  

 public void setConnector(String a) {
        connector = new ClientConnector(a);
    }

    private class ClientConnector implements Runnable {

        private Thread connectorThread;

        String connectionURL;
        String a;
        DataOutputStream dataout;
        DataInputStream datain;

        String[] appNames;

        ClientConnector(String a) {
            connectorThread = new Thread(this);
            connectorThread.start();
            this.a = a;

        }


        public void run() {
            connect(a);
        }

        public void connect(String a) {

     a = gui.getBTDevices_listSCRN().getString(gui.getBTDevices_listSCRN().getSelectedIndex());

            connectionURL = (String)hashDevices.get(a);
            System.out.println(connectionURL);

            System.out.println("\n\n\n\n the Device is: "+ a );
            

            //WARNING: DAPAT MAG-MULTITHREAD PARA NDI MAGHANG UNG GUI

            try {
                conn = (StreamConnection) Connector.open(connectionURL);
               
                dataout = conn.openDataOutputStream();
                datain = conn.openDataInputStream();

                scrHandler = new ScreenshotHandler(datain);
               // ListHandler listHandler = new ListHandler(datain, gui);
                dataout.writeUTF(localDevice.getFriendlyName());
                dataout.writeInt(1);
                dataout.writeUTF(localDevice.getBluetoothAddress());
                dataout.writeInt(5); //sabihin sa server na ready na magready na sa messages
                dataout.flush();
                System.out.println("Connection established");
               Display.getDisplay(gui).setCurrent(gui. getMenuMyDoc());


                //dataout = conn.openDataOutputStream();
            } catch (IOException e) {
                System.err.println("Note: can't connect to: " + connectionURL);
            }


   
        }
    }
}


and this is the server code


import javax.bluetooth.*;
//import com.intel.bluetooth.*;
import javax.microedition.io.*;

import java.io.IOException;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.DataOutputStream;
import java.io.*;
import java.util.Hashtable;
import java.util.Scanner;
import javax.microedition.io.Connector;
import javax.obex.*;
/**
 *
 * @author ding
 */
public class Server implements Runnable {

    ThesisServerView view;
 private DirectoryReader Reader;
    private LocalDevice localDevice; // local Bluetooth Manager
    private DiscoveryAgent discoveryAgent; // discovery agent

    /** Keeps the information about this server. */
    private ServiceRecord record;

    // Bluetooth Service name
    private static final String myServiceName = "MCFC Server";


    private static final UUID MCFC_SERVER_UUID = new UUID("F0E0D0C0B0A000908070605040302010", false);

    private static final int MCFC_ATTRIBUTE_ID = 0x1101;


    private final Hashtable hashDevices = new Hashtable();
    String connectionURL;

    private Thread svrThread;

    StreamConnection conn;
    StreamConnectionNotifier scn;

    //boolean done = false;
   // MessageHandler msghandler;
    //MouseController mouse = new MouseController();
    DirectoryReader direct = new DirectoryReader();
    String[] apps;
    int appsArraySize=0;
    String address;
    boolean isAuthorized;
    String name;
    private String path;

     DataOutputStream dataout;
public Server server;
     public Server(ThesisServerView parent) {
            view = parent;
        isAuthorized = true;

    }
 public void startSvr() {

        svrThread = new Thread(this);
        svrThread.start();

    }
public int onGet(Operation op) {
try{
//The server has received a GET request for client.
System.out.println("Received a GET request from client.... . ");
HeaderSet hdr = op.getReceivedHeaders();
System.out.println("Server has received a request for the file "+
(hdr.getHeader(HeaderSet.NAME)).toString());
String url = "file://name=" +(hdr.getHeader(HeaderSet.NAME)).toString() + ";mode=r";
InputConnection inpcon =(InputConnection)Connector.open(url);
InputStream in = inpcon.openInputStream();
byte[] fileAsBytes = new byte[97];
in.read(fileAsBytes);
System.out.println("File read fully into the port.... ");
for(int i =0; i<fileAsBytes.length; i++)
System.out.print((char)fileAsBytes[i]);
DataOutputStream out = op.openDataOutputStream();
out.write(fileAsBytes, 0, fileAsBytes.length);
System.out.println("\n" + "File written back to client.... ");
op.close();
in.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
return ResponseCodes.OBEX_HTTP_OK;
}
    public void run() {
      
//        prepareAppsList();
        
    try {

            btInit();

        } catch (BluetoothStateException bse) {

        }

        // Define the server connection URL

         connectionURL = "btspp://localhost:"+MCFC_SERVER_UUID.toString()+";"+"name="+myServiceName;

        // request all of the client not to be authorized
        // some devices fail on authorize=true
        connectionURL.concat(";authorize=false");

        // Create a server connection (a notifier)
        try {
        scn = (StreamConnectionNotifier) Connector.open(connectionURL);

         StreamConnection filestream =(StreamConnection)Connector.open("btgoep://localhost:1106;name=FTP");
          dataout = filestream.openDataOutputStream();
        record = localDevice.getRecord(scn);
        conn = scn.acceptAndOpen();
        DirectoryReader read = new DirectoryReader();
          DataInputStream in = conn.openDataInputStream();
        DataOutputStream out = conn.openDataOutputStream();
         name = in.readUTF(); //get the name of the

        in.readInt();

         address = in.readUTF();

        if (!checkClient(address)) {
            in.close();
            out.close();
            conn.close();
            scn.close();
            isAuthorized = false;
            svrThread = new Thread(this);
            svrThread.start();
            isAuthorized = false;
            startSvr();
        } else {



       // msghandler = new MessageHandler(view, in, out, mouse);
       // AppsListSender listSender = new AppsListSender(apps, appsArraySize, out);
       // listSender.startSend();
       System.out.println("abot d2");
            if (in.readInt() == 5) {
               /* while (msghandler.done == false) {


                    //readMessage(in);
                    view.log("\nWaiting command from client...\n");
                    msghandler.readMessage();
                    System.out.println("done is "+msghandler.done);
                    //readMessage(in);
                }*/
            }
        }
        } catch (IOException e) {
            System.out.println(e);
        }
        System.out.println("e d2 abot ba dito??!?!?!");
    }

    public void btInit() throws BluetoothStateException {
        localDevice = null;
        discoveryAgent = null;

        // Retrieve the local device to get to the Bluetooth Manager
        localDevice = LocalDevice.getLocalDevice();
        // Servers set the discoverable mode to GIAC
        localDevice.setDiscoverable(DiscoveryAgent.GIAC);
        // Clients retrieve the discovery agent
        discoveryAgent = localDevice.getDiscoveryAgent();

    }

    public void prepareAppsList() {
                try
        {
            //create filereader, passing filename
            //String filename = "sometext.txt";
            FileReader fr1 = new FileReader(new File("programs.BDCSS"));
            FileReader fr2 = new FileReader(new File("programs.BDCSS"));
            System.out.println("here\n");
                //pass filereader to scanner
            Scanner scan1 = new Scanner(fr1);
            Scanner scan2 = new Scanner(fr2);
                //loop through the file content
            System.out.println("1\n");
            //appsArraySize=0;

            //get # of lines in file
            while(scan1.hasNextLine())//check that there is more
            {
                appsArraySize += 1;
                //System.out.println(scan.nextLine());	}
                //frame.log(scan.nextLine());
                //String str = scan.nextLine();
                //frame.log(str+"\n");
                //frame.log2(str.substring((str.indexOf('=')+1), str.lastIndexOf(';'))+"\n");
                System.out.println(scan1.nextLine()+"\n");

            }
            apps = new String[appsArraySize];

            //get substring APP in each line
            int j=0;
            String str;
            while(scan2.hasNextLine()) {
                str = scan2.nextLine();
                apps[j] = str.substring((str.indexOf('=')+1), str.lastIndexOf(';'));
                //apps[j] = scan2.nextLine();
                System.out.println(apps[j]+"\n");
                j++;
            }

            scan1.close();
            scan2.close();
            fr1.close();
            fr2.close();
        }

            //an exception has been thrown
        catch(IOException ioe)
        {
                //output the details
            System.out.println(ioe);
            ioe.printStackTrace();
        }
    }

    public boolean checkClient(String address) {
        try {
            FileReader fr = new FileReader(new File("clients.BDCSS"));

            Scanner scan = new Scanner(fr);


            while(scan.hasNextLine()) {

                if (address.equalsIgnoreCase(scan.nextLine())) {
                    return true;
                }
                //str = scan2.nextLine();
                //apps[j] = str.substring((str.indexOf('=')+1), str.lastIndexOf(';'));
                //apps[j] = scan2.nextLine();
                //System.out.println(apps[j]+"\n");
                //j++;
            }

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

        return false;
    }
}


another is the part of the server that access My Document folder

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.File;


public class DirectoryReader {
  public static void main(String[] args) {

    File folder = new File("C:/Users/Satellite/Documents");
    File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
        System.out.println("File " + listOfFiles[i].getName());
      } else if (listOfFiles[i].isDirectory()) {
        System.out.println("Directory " + listOfFiles[i].getName());
      }
    }
  }

}



all it do is just connection and nothing more..

i need to display the file names of the files of My document in my mobile.. but i don't know how to send the bytes on my mobile and display the file names on the mobile.

i also don't know on what to do on the client part so that it display the file names..
Was This Post Helpful? -1
  • +
  • -

#11 steveparker  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 26-May 10

Re: how to view My Document files in mobile using bluetooth client server

Posted 26 May 2010 - 09:07 AM

There are lots of problem in mobile development, I get lots of knowledge through this thread.
Was This Post Helpful? 0
  • +
  • -

#12 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

Re: how to view My Document files in mobile using bluetooth client server

Posted 27 May 2010 - 07:26 PM

can someone help me on how to convert array to byte so that i can send it to mobile. and how to display the file names in the mobile.

or some example

the directory reader code how to convert it so that the data of the file will be sent to the mobile

and as of the mobile,, how to accept it sent data and display the file names on mobile for the user to see which file they want to copy..
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1