ProgressMonitor and SwingWorker aren't working - java

I've got a problem with a SwingWorker. The application sends a file between client and server but the progressmonitor will not be shown me progress during transmission. Could you tell me what i'm doing wrong and what should i do?
The main class is the same for both applications:
package main;
import java.awt.EventQueue;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Test2 test2=new Test2();
}
});
}
}
Client:
package main;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Test2 {
public Test2() {
hostName="localhost";
try {
clientSocket = new Socket(hostName, 1234);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file=new File("E:/test/123.mp4");
try {
fileInputStream=new FileInputStream(file);
bis=new BufferedInputStream(fileInputStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos=new BufferedOutputStream(clientSocket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bit=new byte[512];
int len;
System.out.println("Send..."); //test
try {
while ((len = bis.read(bit,0,511)) != -1) {
bos.write(bit, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bis.close();
bos.close();
fileInputStream.close();
//fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Finish"); //test
}
private String hostName;
private Socket clientSocket;
private BufferedInputStream bis;
private BufferedOutputStream bos;
private FileInputStream fileInputStream;
private byte bit[];
}
Server:
package main;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
public class Test2 {
public Test2() {
pm=new ProgressMonitor(null, "Download...", null, 0, 1850297);
pm.setMillisToDecideToPopup(1);
test4=new Test4();
test4.execute();
}
private class Test4 extends SwingWorker<Boolean, Void> {
public Test4() {
try {
welcomeSocket = new ServerSocket(1234);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Server works");
try {
connectionSocket = welcomeSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Boolean doInBackground() throws Exception {
try {
bis=new BufferedInputStream(connectionSocket.getInputStream());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fileOutputStream=new FileOutputStream("E:/test2/123.mp4");
bos=new BufferedOutputStream(fileOutputStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bit=new byte[512];
int len;
System.out.println("Download..."); //test
try {
while ((len = bis.read(bit,0,511)) != -1) {
bos.write(bit, 0, len);
publish();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bis.close();
bos.close();
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void process(List<Void> chunks) {
number++;
pm.setProgress(number);
}
#Override
protected void done() {
System.out.println("DONE");
}
}
private ServerSocket welcomeSocket;
private Socket connectionSocket;
private FileOutputStream fileOutputStream;
private BufferedInputStream bis;
private BufferedOutputStream bos;
private byte bit[];
private ProgressMonitor pm;
private Test4 test4;
private int number;
}
Apart from SwingWorker, I've got a problem with a code below. This is second version my server's application without a SwingWorker. Here, the progressmonitor is shown me progress during transmission, but not ever. I used invokeLater in run() method but sometimes the progressmonitor isn't work. Could you tell me what i'm doing wrong?
Server:
package main;
import java.awt.EventQueue;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
public class Test2 {
public Test2() {
pm=new ProgressMonitor(null, "Download...", null, 0, 1850297);
pm.setMillisToDecideToPopup(1);
test3=new Test3();
new Thread(test3).start();
}
private class Test3 implements Runnable {
public Test3() {
}
#Override
public void run() {
try {
welcomeSocket = new ServerSocket(1234);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Server works"); //test
while(true){
try {
connectionSocket = welcomeSocket.accept();
try {
bis=new BufferedInputStream(connectionSocket.getInputStream());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fileOutputStream=new FileOutputStream("E:/test2/123.mp4");
bos=new BufferedOutputStream(fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bit=new byte[512];
int len;
System.out.println("Download..."); //test
try {
while ((len = bis.read(bit,0,511)) != -1) {
bos.write(bit, 0, len);
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
number++;
pm.setProgress(number);
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bis.close();
bos.close();
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("DONE"); //test
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private ServerSocket welcomeSocket;
private Socket connectionSocket;
private FileOutputStream fileOutputStream;
private BufferedInputStream bis;
private BufferedOutputStream bos;
private byte bit[];
private ProgressMonitor pm;
private Test3 test3;
private int number;
}

You're waiting on the socket connection and accepting it in the Test4 constructor which will be called on the Swing event thread. It's OK to create the socket there, but don't wait for the connection there as this blocks. Instead wait for the connection it in the doInBackground method.
Also consider changing your SwingWorker so it passes the bytes read:
// change generic parameter to Integer
private class Test4 extends SwingWorker<Boolean, Integer> {
#Override
protected Boolean doInBackground() throws Exception {
// .....
bit=new byte[512];
int len;
try {
while ((len = bis.read(bit,0,511)) != -1) {
bos.write(bit, 0, len);
publish(len);
}
and elsewhere:
#Override
protected void process(List<Integer> chunks) {
// number++;
for (Integer chunk : chunks) {
pm.setProgress(chunk);
}
}

Related

how to update my jframe in a server_client game?

I'm working on a server-client game in which I need to update client's JFrame from the server in a specific period.this is my game
The problem is that the client's JFrame does not update.to be sure,I have rendered the JFrame Submitted by the server and it's OK,but the client's JFrame does not change at all.Here's my code:
my server:
public class main implements java.io.Serializable{
static ArrayList<Socket> allsockets = new ArrayList<>();
static ArrayList<ObjectOutputStream> oos = new ArrayList<>();
static final MainFrame frame=new MainFrame();
static boolean testfirst=false;
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
// TODO Auto-generated method stub
String name;
String color;
Color color1 = null;
Socket clientsocket=null;
ServerSocket serversocket=null;
PrintStream os = null;
ObjectInputStream is=null;
try{
serversocket = new ServerSocket(); // don't bind just yet
serversocket.setReuseAddress(true);
serversocket.bind(new InetSocketAddress(5555)); // can bind with reuse= true
}
catch(IOException e){
System.out.println(e);
}
while(true){
try {
clientsocket=serversocket.accept();
allsockets.add(clientsocket);
oos.add(new ObjectOutputStream(clientsocket.getOutputStream()));
is=new ObjectInputStream(clientsocket.getInputStream());
os = new PrintStream(clientsocket.getOutputStream());
try {
name =(String) is.readObject();
color=(String) is.readObject();
try {
java.lang.reflect.Field field = Class.forName("java.awt.Color").getField(color);
color1 = (Color)field.get(null);
} catch (Exception e) {
color = null;
}
player p=new player();
frame.addplayer(name, color1,p);
if(!testfirst){
testfirst=true;
new Thread(){
public void run(){
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("timer works");
for(ObjectOutputStream os:oos){
try {
os.writeObject(frame);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 1, 1);
}
}.start();
}
handle h= new handle(is, frame, p);
h.start();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
my client:
public class client implements java.io.Serializable {
static private final Lock mutex = new ReentrantLock(true);
private static final long serialVersionUID = 1L;
static double prevx =0;
static double prevy=0;
static Timer timer=new Timer();
static ObjectOutputStream os =null;
public static void main(String[]args) {
MainFrame frame=new MainFrame();
Socket clientSocket=null;
ObjectInputStream is=null;
String name;
String color;
try {
clientSocket = new Socket("localhost", 5555);
os = new ObjectOutputStream(clientSocket.getOutputStream());
is=new ObjectInputStream(clientSocket.getInputStream());
System.out.println("enter your name:");
Scanner in1=new Scanner(System.in);
name=in1.nextLine();
System.out.println("enter your color:");
color=in1.nextLine();
in1.close();
os.writeObject(name);
os.writeObject(color);
refresh ref=new refresh( is, os);
ref.start();
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to host");
}
}}
the refresh class(which has the responsibility to update client's JFrame)
public class refresh extends Thread{
MainFrame frame;
ObjectInputStream ois;
ObjectOutputStream oos;
Timer timer=new Timer();
double prevx,prevy;
private Lock mutex = new ReentrantLock(true);
public refresh(ObjectInputStream ois,ObjectOutputStream oos){
frame=new MainFrame();
this.ois=ois;
this.oos=oos;
}
public void run(){
while(true){
try {
frame= (MainFrame) ois.readObject();
frame.repaint();
frame.removeMouseMotionListener(mml);
frame.addMouseMotionListener(mml);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setFocusable(true);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MouseMotionListener mml=new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
mutex.lock();
try {
System.out.println("mouse moved");
oos.writeObject(arg0.getX());
oos.writeObject(arg0.getY());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mutex.unlock();
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
};}
and if needed the handle class(which receives the mouse coordinates from the client)
public class handle extends Thread{
double prevx,prevy;
MainFrame frame;
player myplayer;
ObjectInputStream ois;
double screenwidth,screenheigth;
boolean first=false;
boolean finished = false;
static private final Lock mutex = new ReentrantLock(true);
Thread movethread = new Thread(){
public void run(){
System.out.println("movethread run");
try {
if(Math.abs(prevx-myplayer.xcenter)>1 || Math.abs(prevy - myplayer.ycenter)>1){
while(Math.abs(prevx-myplayer.xcenter)!=0
|| Math.abs(prevy - myplayer.ycenter)!=0){
if(prevx<0 || prevx>screenwidth || prevy<0 || prevy>screenheigth)break;
myplayer.movem(prevx, prevy,mutex);
frame.repaint();
System.out.println(myplayer.cp.getCenter());
}
finished = true;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public handle(ObjectInputStream ois,MainFrame frame,player p) {
// TODO Auto-generated constructor stub
this.myplayer=p;
this.ois=ois;
this.frame=frame;
this.screenwidth=frame.getscreenwidth();
this.screenheigth=frame.getscreenheigth();
}
public void run(){
System.out.println("handle thread run");
while(true){
try {
System.out.println("in handle");
System.out.println(first);
prevx= (double) ois.readObject();
prevy=(double) ois.readObject();
if(!first){
System.out.println("movethread started");
movethread.start();
first = true;
}
else if(first && finished){
movethread.run();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void update(double x,double y){
this.prevx=x;
this.prevy=y;
}}
Any help would be appreciated.

sleep between two function in android java?

I Have class to record sound in my android project .
In this class i have 2 function : start() and stop()
and i have a main class I want run it from other activity such : record(second)
and record some time and stop aoutomaticly after those second !
Like this :
start();
//sleep(second)
stop();
How I can do this ?
this is my code :
package com.example.voicerec;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.view.View;
public class VoiceR {
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private String outputFile = null;
public void Record()
{
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/momeni.3gpp";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setOutputFile(outputFile);
}
public void start(View view) {
try {
myRecorder.prepare();
myRecorder.start();
}
catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
}
catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
}
public void stop(View view) {
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
}
catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
}
catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void play(View view) {
try {
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Just make a thread that runs start then sleeps for record time then runs stop :
final int time = second * 1000;
Thread sound = new Thread(new Runnable() {
#Override
public void run() {
start(view);
try{
Thread.sleep(time);
}catch(Exception e){}
stop();
}
});
sound.start();
or you can use CountDownLatch :
CountDownLatch latch = new CountDownLatch(1);
start(view);
Thread stopping = new Thread(new Runnable() {
#Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stop(view);
}
});
stopping.start();
and after the recording process finished:
latch.countDown();

Java network client-server (file sneding), stuck in client receive loop

i tried to make a simple client-server (with some gui) the server sends the data and the client receive it (the save of the file works too) but the client seems to be stucked in the receive-loop.
I started both threads with ".start()".
I have marked the position of the problem with bold style.
My some of you have a idea why the programm in the client dont goes on... - best wishes ghali
Server:
public class Server extends Thread implements Runnable{
public File choosenfile;
public int port = 42001;
public boolean running = true;
public String myAdress = "localhost";
public ServerSocket serverSocket;
public BufferedInputStream bis;
public boolean debug = true;
public OutputStream os;
public void run() {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(running){
Socket socket = null;
try {
System.out.println("Listening on port: "+port);
socket = serverSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Dies ist die stelle an der man einen Thread aufmachen kann
*/
// 1. File-Hülle anlegen dazu muss man deren größere wissen
if(debug) System.out.println("Server: 1.");
int count;
byte[] buffer = new byte[1024];
try {
os = socket.getOutputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(choosenfile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
while ((count = in.read(buffer)) > 0) {
os.write(buffer, 0, count);
os.flush();
}
} catch (IOException e1) {
e1.printStackTrace();
}
if(debug) System.out.println("Server: finish sending");
try {
os.flush();
if(debug) System.out.println("Server: close");
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
running =false;
}
}
}
Client:
public class Client extends Thread implements Runnable{
public Gui gui; //graphical surface
public boolean running = true;
public boolean debug =true;
//Networkstuff
Socket socket;
DataInputStream is;
public byte[] returnFile;
public Client(Gui gui){
this.gui = gui;
}
public void run() {
try {
socket = new Socket(InetAddress.getByName(gui.inetAdress),gui.portServer);
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(gui.path);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedOutputStream out = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int count;
InputStream in = null;
try {
in = socket.getInputStream();
int i =0;
}
catch (IOException e1) {
e1.printStackTrace();
}
try {
while((count=in.read(buffer)) >0){
fos.write(buffer, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**//folloing functions are not executed anymore and i dont know why**
gui.loadPicture();
try {
fos.close();
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
It's quite simple. read() blocks until
data is available in the stream, or
the stream is closed
The server sends bytes to the stream, but never closes it, so the client reading from this stream doesn't have any way to know if some more data will come or not, so it blocks.
Close the stream at server-side, or design a protocol allowing the client to know when to stop reading (like for example sending the number of bytes in the file, then sending these bytes).

Datagram socket isn't receiving

I have a server-client basis going on here but it seems that when the server and client handshake I can get the server to send a message back to the client.
This is the server side
package me.game.net;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import me.game.WorldOfTrade;
public class NetServerHandler implements Runnable {
public static final int max_packet_size = 512;
public static final int max_clients = 5;
DatagramSocket socket;
List<DatagramSocket> connectedClients;
public NetServerHandler(short port) {
try {
socket = new DatagramSocket(port);
connectedClients = new ArrayList<DatagramSocket>();
} catch (SocketException e) {
System.out.println("Failed to initialize the server...");
e.printStackTrace();
}
}
public boolean handlePacket(byte[] pck, InetAddress add) throws IOException{
String str = new String(pck);
str = str.trim();
if(str.equalsIgnoreCase("ping")){
System.out.println("Client ==>> Us: ping");
sendPacket(easyPacket("pong").getData(), add);
return true;
}
return false;
}
public DatagramPacket easyPacket(String buffer){
byte[] buff = buffer.getBytes();
return new DatagramPacket(buff, buff.length);
}
public void run() {
System.out.println("Running server!");
new Thread(new Runnable() {
#Override
public void run() {
while(WorldOfTrade.isRunning){
DatagramPacket pck = new DatagramPacket(new byte[max_packet_size], max_packet_size);
try {
socket.setSoTimeout(200);
socket.receive(pck);
DatagramSocket newSocket = new DatagramSocket();
newSocket.connect(pck.getAddress(), 25565);
if(connectedClients.size() > 0){
continue;
}
connectedClients.add(newSocket);
System.out.println("Found new client! "+new String(pck.getData()));
sendPacket(easyPacket("pong").getData(), pck.getAddress());
} catch (IOException e) {
if(!(e instanceof SocketTimeoutException)){
e.printStackTrace();
}
}
}
}
}
).start();
while (WorldOfTrade.isRunning) {
if(connectedClients.isEmpty()){
continue;
}
int i = 0;
//System.out.println("Checking "+i);
DatagramSocket sck = socket;
DatagramPacket pck = new DatagramPacket(new byte[max_packet_size], max_packet_size);
try {
sck.setSoTimeout(0);
sck.receive(pck);
} catch (IOException e) {
if(e instanceof SocketTimeoutException){
}else{
e.printStackTrace();
}
}
try {
if(!handlePacket(pck.getData(), pck.getAddress())){
//sendPacket(easyPacket("pong").getData(), i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
public void sendPacket(byte[] buffer, InetAddress add) throws IOException {
if(buffer.length > max_packet_size){
System.out.println("Couldnt send packet because it was to big!");
return;
}
DatagramPacket pck = new DatagramPacket(buffer, buffer.length, add, 25565);
System.out.println("Sending packet to "+add.getHostAddress()+":"+25565);
socket.connect(add, 25565);
socket.send(pck);
}
}
This is the client side
package me.game.net;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import me.game.WorldOfTrade;
public class NetHandler implements Runnable {
DatagramSocket sck;
public NetHandler(String connect){
try {
sck = new DatagramSocket();
sck.connect(InetAddress.getByName(connect), (short)25565);
sck.setSoTimeout(0);
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
}
}
public boolean handlePacket(byte[] pck) throws IOException{
String str = new String(pck);
str = str.trim();
System.out.println("Recieved Packet: "+str);
if(str.equalsIgnoreCase("pong")){
System.out.println("Server ==>> Us : pong");
return true;
}
System.out.println("!");
return false;
}
public DatagramPacket easyPacket(String buffer){
byte[] buff = buffer.getBytes();
return new DatagramPacket(buff, buff.length);
}
public void run() {
System.out.println("Running client connector!");
boolean timedOut = false;
try {
sendPacket(easyPacket("ping").getData(), sck);
} catch (IOException e) {
e.printStackTrace();
}
int update = 0;
while (WorldOfTrade.isRunning) {
if(WorldOfTrade.frame == null){
continue;
}
WorldOfTrade.frame.setTitle("Timed Out: "+timedOut);
update++;
if (update % 2 == 0) {
try {
sendPacket(easyPacket("ping").getData(), sck);
} catch (IOException e) {
e.printStackTrace();
}
}else{
DatagramPacket pck = new DatagramPacket(new byte[NetServerHandler.max_packet_size], NetServerHandler.max_packet_size);
while(true){
try {
//System.out.println("Client: Listening for packet "+System.currentTimeMillis());
sck.setSoTimeout(500);
sck.receive(pck);
System.out.println(new String(pck.getData()));
handlePacket(pck.getData());
timedOut = false;
break;
} catch (SocketTimeoutException e) {
// if(e instanceof SocketTimeoutException){
// timedOut = true;
// continue;
// }
try {
sendPacket(easyPacket("ping").getData(), sck);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
sck.close();
}
public void sendPacket(byte[] buffer, DatagramSocket sck) throws IOException {
if(buffer.length > NetServerHandler.max_packet_size){
System.out.println("Couldnt send packet because it was to big!");
return;
}
DatagramPacket pck = new DatagramPacket(buffer, buffer.length, sck.getInetAddress(), 25565);
sck.send(pck);
}
}

Android : My app crashes when there is a blank editText field

I have a problem with my code.
It keeps on crashing when i have a blank editText field.
This bit of code is in the settings of my app and works the data fine but when there is a blank field it crashes the program.
Here's the code for it.
Please don't be harsh because it is my 1st android app. So if anyone knows how to solves the blank edit text field problem that would be greatly appreciated! (Any other comments on how to improve the app would be a help to).
Cheers
package com.cleanyet.cyv100fp;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class sTasks extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tasks);
/*Sets Up the Variables*/
Button done = (Button) findViewById(R.id.done1);
EditText t1 = (EditText)findViewById(R.id.tbTask1);
EditText t2 = (EditText)findViewById(R.id.tbTask2);
EditText t3 = (EditText)findViewById(R.id.tbTask3);
EditText t4 = (EditText)findViewById(R.id.tbTask4);
EditText t5 = (EditText)findViewById(R.id.tbTask5);
String FILENAME1 = "stask1";
String FILENAME2 = "stask2";
String FILENAME3 = "stask3";
String FILENAME4 = "stask4";
String FILENAME5 = "stask5";
String task1 = null;
String task2 = null;
String task3 = null;
String task4 = null;
String task5 = null;
String edit = "Edit Task";
/*Fixes the Blank Field bug*/
/*Sets up the file input*/
FileInputStream fis = null;
/*Gets the tasks set previously*/
/*Task 1 set up*/
try {
fis = openFileInput(FILENAME1);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task1 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task1.toString().length() < 0) {
task1.toString();
t1.setText(task1);
}
else {
t1.setText(edit);
}
/*Task 2 set up*/
try {
fis = openFileInput(FILENAME2);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task2 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task2.toString().length() < 0) {
task2.toString();
t2.setText(task2);
}
else {
t2.setText(edit);
}
/*Task 3 set up*/
try {
fis = openFileInput(FILENAME3);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task3 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task3.toString().length() < 0) {
task3.toString();
t3.setText(task3);
}
else {
t3.setText(edit);
}
/*Task 4 set up*/
try {
fis = openFileInput(FILENAME4);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task4 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task4.toString().length() < 0) {
task4.toString();
t4.setText(task4);
}
else {
t4.setText(edit);
}
/*Task 5 set up*/
try {
fis = openFileInput(FILENAME5);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task5 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task5.toString().length() < 0) {
task5.toString();
t5.setText(task5);
}
else {
t5.setText(edit);
}
/*When changes have been made and done is clicked*/
done.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/*Sets up the Variables*/
EditText t1 = (EditText)findViewById(R.id.tbTask1);
EditText t2 = (EditText)findViewById(R.id.tbTask2);
EditText t3 = (EditText)findViewById(R.id.tbTask3);
EditText t4 = (EditText)findViewById(R.id.tbTask4);
EditText t5 = (EditText)findViewById(R.id.tbTask5);
String tasks1 = t1.getText().toString();
String tasks2 = t2.getText().toString();
String tasks3 = t3.getText().toString();
String tasks4 = t4.getText().toString();
String tasks5 = t5.getText().toString();
String FILENAME1 = "stask1";
String FILENAME2 = "stask2";
String FILENAME3 = "stask3";
String FILENAME4 = "stask4";
String FILENAME5 = "stask5";
String task1 = tasks1;
String task2 = tasks2;
String task3 = tasks3;
String task4 = tasks4;
String task5 = tasks5;
String edit = "Go to settings to make this task.";
if (t1 != null){
t1.setText(edit);
/*t2.setText(edit);
t3.setText(edit);
t4.setText(edit);
t5.setText(edit);*/
};
/*Put if statement here to catch the empty field*/
/*Makes The Changes to the Tasks*/
try {
FileOutputStream fos1 = openFileOutput(FILENAME1, Context.MODE_PRIVATE);
fos1.write(task1.getBytes());
fos1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos2 = openFileOutput(FILENAME2, Context.MODE_PRIVATE);
fos2.write(task2.getBytes());
fos2.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos3 = openFileOutput(FILENAME3, Context.MODE_PRIVATE);
fos3.write(task3.getBytes());
fos3.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos4 = openFileOutput(FILENAME4, Context.MODE_PRIVATE);
fos4.write(task4.getBytes());
fos4.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos5 = openFileOutput(FILENAME5, Context.MODE_PRIVATE);
fos5.write(task5.getBytes());
fos5.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent("com.checkin.cyv100fp.settings"));
}
});
}
}
if (task1.toString().length() < 0) {
task1.toString();
t1.setText(task1);
}
else {
t1.setText(edit);
}
The above makes no sense at all.
Firstly task1 IS a string so there's no need to call toString() to convert it to one.
Secondly, your conditional statement (if) is checking to see if task1 has a length less than zero....think about it.
Thirdly, if it does have an impossible length less than zero you then call toString() on it again (with no variable to receive the impossible less than zero result) and you then try to set the text of your t1 EditText.
The chances are that your file reading is failing (probably because you only save the strings later in the onClick(...) method). Because your task strings will be null if the file reading fails then you need to test for null before trying to use them.
In other words you're doing this in your code...
String task1 = null;
To fix the bit of code I enclosed at the beginning, use...
if (task1 != null) {
t1.setText(task1);
}
else {
t1.setText(edit);
}
...but most importantly, make sure your files have the strings in them that you need to read.

Categories