Results 1 to 8 of 8

Thread: need help

  1. #1
    amer is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default need help

    i want to update the code in bellow to be able to send image from computer to mobile using tcp socket
    i add a code to the "method save()" that should save the image in hard disk an then send it by socket to mobile
    it give me error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException in BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));


    could you help me
    with best regard



    the method updated is

    public void save(){
    try{
    ImageIO.write(img, "jpg", new File("dynamics.jpg"));
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    wr.write("image_sending");
    wr.flush();}
    catch(IOException ioe){
    System.err.println("write: " + ioe.getMessage());}
    }


    the code


    public static void main(String args[]){
    try {ServerSocket serverSocket = new ServerSocket(12344);
    toClient = serverSocket.accept();
    Thread desktopServerThread = new Thread(){
    public void run(){
    while(true){
    try {
    in= new BufferedReader(new InputStreamReader(toClient.getInputStream()));
    String str;

    if (!(str=in.readLine()).equals("") | !str.equals(" "))
    // output.write(str.getBytes());
    JFrame frame = new JFrame("Image Label");
    BufferedImage img = null;
    Main tt = new Main(img,"");
    tt.dbTest();
    String imageFileName = "map.png";
    img = ImageIO.read(new File(imageFileName));
    frame.add("Center", new Main(img, ""));

    frame.pack();
    frame.setVisible(true);

    }
    } catch(Exception e) {
    System.out.println("S: Error");
    e.printStackTrace();
    break;
    }
    }
    }
    };
    desktopServerThread.start();

    } catch (Exception e) {
    System.out.println("S: Connection Error");
    e.printStackTrace();
    }

    }

    BufferedImage img;
    String text;
    Font font;


    public Main(BufferedImage img, String text) {

    this.img = img;
    this.text = text;
    font = new Font("Serif", Font.PLAIN, 36);

    }

    public void paint(Graphics g) {

    g=img.getGraphics();
    int[] x= Main.x;
    int[][] A=Main.A;


    Dimension size = getSize();
    g.drawImage(img, 0, 0, 800, 600, this);

    g.setColor(Color.BLACK);
    g.setFont(font);
    FontRenderContext frc = ((Graphics2D) g).getFontRenderContext();
    Rectangle2D bounds = font.getStringBounds(text, frc);

    save();
    }

    public void save(){
    try{ImageIO.write(img, "jpg", new File("dynamics.jpg"));}
    catch(IOException ioe){System.err.println("write: " + ioe.getMessage());}
    }

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default

    error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException in
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    What is the value of the socket variable here?

  3. #3
    amer is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default

    i want to send image from computer to mobile
    i have updated the method save() in the server code
    the method updated is

    public void save(){
    try{
    ImageIO.write(img, "jpg", new File("dynamics.jpg"));
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    wr.write("image_sending");
    wr.flush();}
    catch(IOException ioe){
    System.err.println("write: " + ioe.getMessage());}
    }



    but it give me error
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException in BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));





    server code


    package serverproject;

    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.font.FontRenderContext;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    public class Main extends Component {
    public static int[] x=new int[30] ;
    public static int[] y=new int[30];
    public static int i;
    public static int ij=0;
    public static int[] d=new int[30];
    public static int c = 0;
    public static int[] s=new int[30];
    public static int[] prev=new int[30];
    public static int[] q=new int[30];
    public static int[][] A=new int[300][300] ;
    public static int[] sx=new int[30] ;
    public static int[] sy=new int[30] ;
    public static Graphics g;
    public static int start;
    private static Socket toClient;
    private static BufferedReader in;
    private static InputStream input; // input stream from client
    private static OutputStream output; // outut stream to client
    public static int w=0;
    Socket socket;
    boolean work = true;
    public static int startx;
    public static int starty;
    public static void main(String args[]) {
    try {
    System.out.println("S: Connecting...");
    ServerSocket serverSocket = new ServerSocket(12344);

    toClient = serverSocket.accept();
    System.out.println("S: Connected");
    output = toClient.getOutputStream();

    Thread desktopServerThread = new Thread(){
    public void run(){
    while(true){
    try {
    in= new BufferedReader(new InputStreamReader(toClient.getInputStream()));
    String str;

    if (!(str=in.readLine()).equals("") | !str.equals(" "))
    System.out.println("C: '" + str);
    int b = str.indexOf('d');
    String startpt = str.substring(1, b);
    int bbb=startpt.indexOf(',');
    String bx = startpt.substring(0, bbb);
    String by = startpt.substring(bbb+1);
    startx=Float.valueOf(bx.trim()).intValue();// Integer. parseInt(bx.trim());
    starty=Float.valueOf(by.trim()).intValue();//Integer.parseInt(by.trim());
    String destpt = str.substring(b+1);
    System.out.println("sending :( " + str + " ) to Mobile");

    output.write(str.getBytes());
    System.out.println("Sending Message Succesful"+" s "+startpt+" d "+destpt);
    System.out.println("xx "+startx+" yy "+starty);
    w=1;
    if (w==1){
    JFrame frame = new JFrame("Image Label");
    BufferedImage img = null;
    Main tt = new Main(img,"");
    tt.dbTest();
    String imageFileName = "map.png";
    img = ImageIO.read(new File(imageFileName));
    frame.add("Center", new Main(img, ""));

    frame.pack();
    frame.setVisible(true);//

    }
    } catch(Exception e) {
    System.out.println("S: Error");
    e.printStackTrace();
    break;
    }
    }
    }
    };
    desktopServerThread.start();

    } catch (Exception e) {
    System.out.println("S: Connection Error");
    e.printStackTrace();
    }

    }

    BufferedImage img;
    String text;
    Font font;


    public Main(BufferedImage img, String text) {

    this.img = img;
    this.text = text;
    font = new Font("Serif", Font.PLAIN, 36);

    }

    /* We want to size the component around the text. */
    public Dimension getPreferredSize() {
    FontMetrics metrics = img.getGraphics().getFontMetrics(font);
    int width = metrics.stringWidth(text) * 2;
    int height = metrics.getHeight() * 2;
    return new Dimension(width, height);
    }

    public void paint(Graphics g) {

    g=img.getGraphics();
    int[] x= Main.x;
    int[][] A=Main.A;


    Dimension size = getSize();
    g.drawImage(img, 0, 0, 800, 600, this);

    g.setColor(Color.BLACK);
    g.setFont(font);
    FontRenderContext frc = ((Graphics2D) g).getFontRenderContext();
    Rectangle2D bounds = font.getStringBounds(text, frc);

    for(int j = 0; j <i; j++) {
    g.fillRect(x[j] ,y[j], 15, 15);
    d[j]=1000;

    }

    int c=start;
    int dest=10;


    d[c]=0;
    int m=-1;
    q[c]= -1;
    while (q[i-1]!=-1)
    {

    if (c==dest){
    break;
    }

    int minvalue=1000;
    for (int jj=0;jj<i;jj++){

    if(jj!=c & A[c][jj]!=0 & A[c][jj]!=1000 & q[jj]!=-1){

    int alt=d[c]+A[c][jj];
    if (alt <= d[jj]){
    d[jj]=alt;
    prev[jj]=c;


    }
    if (d[jj]<minvalue){m=jj;
    minvalue=d[jj];


    }
    }
    }
    if (m==c){q[start]=0;}
    if (m!=-1 & m!=c){
    c=m;

    }

    q[c]= -1;

    }
    s[ij]=dest;
    c=dest;
    ij=0;

    while (s[ij]!=start){

    ij=ij+1;
    s[ij]=prev[c];
    c=prev[c];


    }
    for (int ik=0;ik<=ij;ik++){

    sx[ik]=x[s[ik]];
    sy[ik]=y[s[ik]];


    }

    g.drawPolyline(sx, sy, ij+1);

    save();
    }


    void dbTest() {



    DataInputStream dis = null;
    String dbRecord = null;
    DataInputStream diss = null;
    String dbRecordd = null;
    try {

    File f = new File("waypoints.txt");
    File ff = new File("data.txt");
    FileInputStream fis = new FileInputStream(f);
    FileInputStream fiss = new FileInputStream(ff);
    BufferedInputStream bis = new BufferedInputStream(fis);
    BufferedInputStream biss = new BufferedInputStream(fiss);
    dis = new DataInputStream(bis);
    diss = new DataInputStream(biss);
    i=0;


    while ( (dbRecord = dis.readLine()) != null) {

    StringTokenizer st = new StringTokenizer(dbRecord );//":");
    String xxx = st.nextToken();
    String yyy = st.nextToken();



    int xx = Integer.parseInt(xxx.trim());
    int yy = Integer.parseInt(yyy);


    x[i] = xx;
    y[i]=yy;

    if (startx==(xx/10) & starty==(yy/10) ){start=i;
    }
    i=i+1;
    }

    int l=0;
    while ( (dbRecordd = diss.readLine()) != null) {
    int k=0;
    StringTokenizer stt = new StringTokenizer(dbRecordd );//":");
    while(stt.hasMoreTokens()){

    A[l][k] = Integer.parseInt(stt.nextToken());

    k=k+1;
    }
    l=l+1;
    }

    } catch (IOException e) {
    // catch io errors from FileInputStream or readLine()
    System.out.println("Uh oh, got an IOException error: " + e.getMessage());

    } finally {
    // if the file opened okay, make sure we close it
    if (dis != null) {
    try {
    dis.close();
    } catch (IOException ioe) {
    System.out.println("IOException error trying to close the file: " );
    }

    } // end if

    } // end finally


    } // end dbTest

    public void save()

    {

    try

    {


    ImageIO.write(img, "jpg", new File("dynamics.jpg"));

    }

    catch(IOException ioe)

    {

    System.err.println("write: " + ioe.getMessage());

    }

    }

    }


    client code

    package routing;


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


    public class route extends MIDlet implements CommandListener,LocationListener {

    private boolean midletPaused = false;

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">
    private Command exitCommand;
    private Command okCommand;
    private Command okCommand1;
    private Form form;
    private TextField textField1;
    private TextField textField;
    //</editor-fold>
    private Display display;
    public LocationProvider provider;
    public Location location;
    public QualifiedCoordinates qc;
    public String startpt;
    InputStream is;
    OutputStream os;

    public route() {
    display = Display.getDisplay(this);

    try{
    provider = LocationProvider.getInstance(null);
    provider.setLocationListener(this, -1, 0, 0);


    }
    catch ( LocationException e ) { textField1.setString(e.getMessage()); }
    }

    public void sendMessage(String message) throws IOException {
    message = prepare(message);
    byte[] data = message.getBytes();

    os.write(data);
    os.flush();
    System.out.println("message has been sent: " + new String(data));

    }

    public String recieveMessage() throws IOException {


    StringBuffer sb = new StringBuffer();
    int c = 0;
    System.out.println("ddddddddddd: " );
    while (((c = is.read()) != '\n') && (c != -1)) {
    sb.append((char) c);
    }
    System.out.println("eeeeeeeeeeeeee " );
    System.out.println("recieved from server: " + sb.toString());
    return sb.toString();
    }
    public void sendMessageToServerAndReadResponse() {
    try {
    sendMessage( "s"+startpt+"d"+textField.getString());
    recieveMessage();//00
    } catch (IOException ex) {
    //
    return;
    }


    }


    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">
    /**
    * Initilizes the application.
    * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
    */
    private void initialize() {
    // write pre-initialize user code here

    // write post-initialize user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">
    /**
    * Performs an action assigned to the Mobile Device - MIDlet Started point.
    */
    public void startMIDlet() {
    PrintStream r = System.out;
    r.println("BEFORE TRY");
    try {
    SocketConnection sc = (SocketConnection) Connector.open("socket://localhost:12344");
    System.out.println("connection is open...");
    os = sc.openOutputStream();

    is = sc.openInputStream();


    } catch (IOException x) {
    x.printStackTrace();
    }
    // write pre-action user code here
    switchDisplayable(null, getForm());
    // write post-action user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">
    /**
    * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
    */
    public void resumeMIDlet() {
    // write pre-action user code here

    // write post-action user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">
    /**
    * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
    * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
    * @param nextDisplayable the Displayable to be set
    */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
    // write pre-switch user code here
    Display display = getDisplay();
    if (alert == null) {
    display.setCurrent(nextDisplayable);
    } else {
    display.setCurrent(alert, nextDisplayable);
    }
    // write post-switch user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">
    /**
    * Called by a system to indicated that a command has been invoked on a particular displayable.
    * @param command the Command that was invoked
    * @param displayable the Displayable where the command was invoked
    */
    public void commandAction(Command command, Displayable displayable) {
    // write pre-action user code here
    if (displayable == form) {
    if (command == exitCommand) {
    // write pre-action user code here
    exitMIDlet();
    // write post-action user code here
    } else if (command == okCommand) {
    // write pre-action user code here

    sendMessageToServerAndReadResponse();
    // write post-action user code here
    }
    }
    // write post-action user code here
    }
    //</editor-fold>


    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">
    /**
    * Returns an initiliazed instance of exitCommand component.
    * @return the initialized component instance
    */
    public Command getExitCommand() {
    if (exitCommand == null) {
    // write pre-init user code here
    exitCommand = new Command("Exit", Command.EXIT, 0);
    // write post-init user code here
    }
    return exitCommand;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">
    /**
    * Returns an initiliazed instance of form component.
    * @return the initialized component instance
    */
    public Form getForm() {
    if (form == null) {
    // write pre-init user code here
    form = new Form("gps", new Item[] { getTextField(), getTextField1() });
    form.addCommand(getExitCommand());
    form.addCommand(getOkCommand());
    form.setCommandListener(this);
    // write post-init user code here
    }
    return form;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField ">
    /**
    * Returns an initiliazed instance of textField component.
    * @return the initialized component instance
    */
    public TextField getTextField() {
    if (textField == null) {
    // write pre-init user code here
    textField = new TextField("destination", "", 32, TextField.ANY);
    // write post-init user code here
    }
    return textField;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField1 ">
    /**
    * Returns an initiliazed instance of textField1 component.
    * @return the initialized component instance
    */
    public TextField getTextField1() {
    if (textField1 == null) {
    // write pre-init user code here
    textField1 = new TextField("gps", "", 320, TextField.ANY);
    textField1.setPreferredSize(200, 200);
    // write post-init user code here
    }
    return textField1;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand ">
    /**
    * Returns an initiliazed instance of okCommand component.
    * @return the initialized component instance
    */
    public Command getOkCommand() {
    if (okCommand == null) {
    // write pre-init user code here
    okCommand = new Command("send", "", Command.OK, 0);
    // write post-init user code here
    }
    return okCommand;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand1 ">
    /**
    * Returns an initiliazed instance of okCommand1 component.
    * @return the initialized component instance
    */
    public Command getOkCommand1() {
    if (okCommand1 == null) {
    // write pre-init user code here
    okCommand1 = new Command("Ok", Command.OK, 0);
    // write post-init user code here
    }
    return okCommand1;
    }
    //</editor-fold>











    public Display getDisplay () {
    return Display.getDisplay(this);
    }

    public void exitMIDlet() {
    switchDisplayable (null, null);
    destroyApp(true);
    notifyDestroyed();
    }
    String prepare(String message) {
    String r = message;
    r = r + "\n";
    return r;
    }

    public void startApp() {
    textField1 = new TextField("GPS", "Searching..", 256, 0);

    if (midletPaused) {
    resumeMIDlet ();
    } else {
    initialize ();
    startMIDlet ();
    }
    midletPaused = false;
    textField1.addCommand(exitCommand);
    // Form form = new Form("Form example");////1
    // try
    // {
    // Image Logo = Image.createImage("dynamics.jpg");
    //
    //
    // //ImageItem(label,Image,layout,alternative text)
    // ImageItem imageitem =new ImageItem("ImageItem Example",Logo,ImageItem.LAYOUT_CENTER,"");
    // form.append(imageitem);
    // }
    // catch (IOException ex)
    // { System.out.println("Exception occurred: "+ex);
    // }
    // display.setCurrent(form);///2
    }

    public void pauseApp() {
    midletPaused = true;
    }

    public void destroyApp(boolean unconditional) {
    }

    public void locationUpdated(final LocationProvider prov, final Location loc) {
    new Thread() {

    public void run() {
    if (loc != null && loc.isValid()) {
    qc = loc.getQualifiedCoordinates();
    if(qc.getLongitude()!=0)
    {
    try{
    sleep(5);
    }catch(Exception e){}
    }

    String coord="Lat:"+qc.getLatitude()+" Lon:"+qc.getLongitude() +"";
    startpt=qc.getLatitude()+","+qc.getLongitude();
    textField1.setString(coord);
    }
    else {
    textField1.setString("Location null or invalid object:\n");
    }
    }
    }.start();
    }



    public void providerStateChanged(LocationProvider arg0, int arg1) {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    }

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default

    but it give me error
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException in BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    What is the value of the variable: socket when the line refered to in the error message is executed? The JVM sees it null. Where is the value set?

  5. #5
    amer is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default

    private static Socket socket;

    ServerSocket serverSocket = new ServerSocket(12344);

    socket = serverSocket.accept();
    output = socket.getOutputStream();

    in= new BufferedReader(new InputStreamReader(socket.getInputStream()));

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default

    Is the value of the socket variable null when the exception happens or what variable is null when it happens?
    socket = serverSocket.accept();
    Is this line from the posted program? I don't see it.

  7. #7
    amer is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default

    public static void main(String args[]) {
    try {
    System.out.println("S: Connecting...");
    ServerSocket serverSocket = new ServerSocket(12344);

    socket = serverSocket.accept(); System.out.println("S: Connected");
    output = socket.getOutputStream();

    Thread desktopServerThread = new Thread(){
    public void run(){
    while(true){
    try {
    in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String str;

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default

    Is the value of the socket variable null when the exception happens or what variable is null when it happens?
    This is what I see in your posted code:
    toClient = serverSocket.accept();
    and
    toClient = serverSocket.accept();
    If you've changed the code since you posted it and not posted the new versions, I'd need a crystal ball to be able to help you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •