Here's my updated code. This is the button being clicked in the class I made separate form the java class you provided. I know it says Ping (disregard that, I'm using the button for testing purposes) I don't see how they would reference each other with the Process P line of code you provided. What do you think?
JButton btnPingComputer = new JButton("PING");
btnPingComputer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String line;
BufferedWriter bw = null;
BufferedWriter writer =null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String lineToRemove = "OU=Workstations";
String s = null;
Process p = null;
try {
p = Runtime.getRuntime().exec("cmd /c start c:\\computerQuery.bat computerName");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer(); // new trial
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
textArea.append(line);
textArea.append(String.format(" %s%n", line));
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(ldapName.size() - 1).getValue();
System.out.println(commonName);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidNameException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Add the parameter to your java program like this :
Process p = Runtime.getRuntime().exec("cmd /c start c:\\batFile.bat computerName");
This will pass parameter_to_pass to the batch file.
For your situation this code should work well:
/*
This java program copies the value from a jTextField, adds it to a predifined value
and send it to command-line as a parameter. All these happens if you click the jButton
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class cmdJavaTest extends JFrame {
JTextField jTextField1 = new JTextField(20);
JButton jButton1 = new JButton("Click");
JLabel jLabel1 = new JLabel();
public cmdJavaTest() {
super("CmdJavaParameterPass");
getContentPane().setLayout(new FlowLayout());
getContentPane().add(jTextField1);
getContentPane().add(jButton1);
getContentPane().add(jLabel1);
jButton1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sendParam();
}
});
setSize(300, 170);
setVisible(true);
}
public void sendParam(){
try{
String val = "Computer"+jTextField1.getText(); //Put whatever you want to pass as a prefix in place of "Computer"
jLabel1.setText(val);
Process p ;
p = Runtime.getRuntime().exec("cmd /c start c:\\batFile.bat "+val+"");
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String argv[]) {
new cmdJavaTest();
}
}
Use this as you test batch file content
#dsquery computer -name %1
pause
But you must also see how to use a ProcessBuilder.
Thanks, hope it helps
Related
I have a problem with listening to my server output. I would like to be able to print something to the console as soon as one of the quoted command. The problem that I face is that it seems to be listening but then not go along with the rest of the program. So when I try to click on a button on my GUI, it get stuck.
public class MainFrame implements Runnable {
//declare Jpanel
private static JFrame frmHome;
// The client socket
private static Socket clientSocket = null;
// The output stream
static ObjectOutputStream os;
// The input stream
static ObjectInputStream is;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static void main(String[] args) throws IOException{
// The default port.
int portNumber = 3333;
// The default host.
String host = "localhost";
/*
* Open a socket on a given host and port. Open input and output streams.
*/
try {
clientSocket = new Socket(host, portNumber);
is = new ObjectInputStream(clientSocket.getInputStream());
os = new ObjectOutputStream(clientSocket.getOutputStream());
os.flush();
System.out
.println("CONNECTED TO SERVER\n"
+ "Now using host=" + host + ", portNumber=" + portNumber);
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host "
+ host);
}
/*
* If everything has been initialized then we want to write some data to the
* socket we have opened a connection to on the port portNumber.
*/
if (clientSocket != null && os != null && is != null) {
/* Create a thread to read from the server. */
new Thread(new MainFrame()).start();
os.writeObject("Home");
os.flush();
}
}
public void run() {
/*
* Keep on reading from the socket till we receive "Bye" from the
* server. Once we received that then we want to break.
*/
MainFrame window = new MainFrame();
MainFrame.frmHome.setVisible(true);
String responseLine;
try {
while (!closed) {
Here is where I try to create my buffer reader. The 2 commands "Modify,OK" and "AdStudent ok", are coming after other parts of the GUI have successfully performed a task.
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line;
try {
while((line = br.readLine()) != null){
if (br.readLine().contains("Modify,OK")
|| br.readLine().contains("AddSudent ok")){
System.out.println("did it");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} finally{
try {
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public MainFrame() {
initialize();
}
//function to make window visible
void setVisible() throws IOException {
main(null);
}
private void initialize() {
//Initialise Main window with 3 options.
frmHome = new JFrame();
frmHome.setTitle("Home");
frmHome.setBounds(100, 100, 300, 372);
frmHome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHome.getContentPane().setLayout(null);
frmHome.setResizable(false);
JLabel lblWelcomeToSrs = new JLabel("Welcome to SRS");
lblWelcomeToSrs.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblWelcomeToSrs.setBounds(86, 183, 112, 14);
frmHome.getContentPane().add(lblWelcomeToSrs);
//initialise all buttons and labels of window.
JButton btnAdStu = new JButton("Add a student");
btnAdStu.setBounds(10, 207, 126, 23);
btnAdStu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
AddStudentFrame adus;
try {
try {
adus = new AddStudentFrame();
adus.setVisible();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frmHome.setVisible(false);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
frmHome.getContentPane().add(btnAdStu);
JButton btnCheckStud = new JButton("Search / Modify");
btnCheckStud.setBounds(146, 207, 127, 23);
btnCheckStud.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
SearchFrame searchFrame;
searchFrame = new SearchFrame();
searchFrame.setVisible();
}
});
frmHome.getContentPane().add(btnCheckStud);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBounds(0, 0, 0, 0);
frmHome.getContentPane().add(lblNewLabel);
JLabel lblCreatedByRmi = new JLabel("Created by R\u00E9mi Tuyaerts");
lblCreatedByRmi.setBounds(147, 318, 184, 14);
frmHome.getContentPane().add(lblCreatedByRmi);
JButton btnNewButton = new JButton("Complete List of Students");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CompleteListFrame studentList = new CompleteListFrame();
studentList.setVisible();
}
});
btnNewButton.setBounds(52, 241, 184, 23);
frmHome.getContentPane().add(btnNewButton);
// wonderful pictures of his excellence design by Yasser
JLabel lblNewLabel_1 = new JLabel("");
Image img = new ImageIcon(frmHome.getClass().getResource("/michaelchung.jpg")).getImage();
lblNewLabel_1.setIcon(new ImageIcon(img));
lblNewLabel_1.setBounds(80, 11, 120, 148);
frmHome.getContentPane().add(lblNewLabel_1);
}
}
I don't know why but when I export my project into an executable jar file, there are somethings that don't turn out as if you would run the program from eclipse. One frame doesn't open up, which just contains text in it. I have another internal frame which is a split pane and contains questions on the right hand side and information on the left hand side panel. But in the executable jar file it doesn't show the information on the left hand side. I don't know why this is happening, I also have tried many options when exporting the project (making a jar file) but nothing seems to work. Any help would be appreciated.
Here is my code for the frame that doesn't open up:
public class About implements ActionListener, InternalFrameListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
private MyInternalFrame frame;
public About(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(frame == null || frame.getParent() == null && !frame.isIconifiable()){
frame = new MyInternalFrame("SAD Imaging");
try {
in = new BufferedReader(new FileReader("SADInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Tarea = new JTextArea();
//System.out.println(file);
Tarea.setText(file);
Font f = new Font("TimesNewRoman", Font.ROMAN_BASELINE, 16);
Tarea.setFont(f);
Tarea.setBackground(Color.white);
Tarea.setAlignmentX(SwingConstants.CENTER);
Tarea.setEditable(false);
JPanel panel = new JPanel();
panel.add(Tarea);
panel.setBackground(Color.white);
//scroll = new JScrollPane(Tarea);
scroll = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//open the frame in the middle of the desktop.
Dimension desktopSize = desk.getSize();
Dimension jInternalFrameSize = frame.getSize();
frame.setLocation((desktopSize.width - jInternalFrameSize.width)/2, (desktopSize.height- jInternalFrameSize.height)/2);
frame.add(scroll);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
frame.addInternalFrameListener(this);
}
else {
try {
//frame.setIcon(true);
frame.setMaximizable(true);
frame.setIconifiable(false);
frame.setSelected(true);
frame.moveToFront();
frame.toFront();
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame(String title) {
super(title, true,true, true, true);
setSize(600,500);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition * openFrameCount);
}
}
This file just contains text information.
Same problem with the split pane. Here is the code for it.
public class FrequentQuestions implements ActionListener, InternalFrameListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
JPanel panelQuestions = new JPanel();
JPanel panelAnswers = new JPanel();
JTextArea text = new JTextArea();
JTextPane tPane = new JTextPane();
String file ="";
//private FrequentQuestions quest;
JSplitPane pane ;
MyInternalFrame frame;
public FrequentQuestions(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(frame == null || frame.getParent() == null){
frame = new MyInternalFrame("Frequently Asked Questions");
String [] options = {"How to open/save images", "What formats can SAD Imaging open", "How to show information about an image",
"Compute FFT/Inverse", "Graphs"};
JList list = new JList(options);
//list.setBorder(BorderFactory.createLineBorder(Color.black));
//panelQuestions.add(list);
list.addListSelectionListener(new ListSelectionListener(){
#Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
if(e.getValueIsAdjusting() == false)
return;
JList list = (JList) e.getSource();
if (list.isSelectionEmpty()) {
System.out.println("list selection is empty!");
}
int index = ((JList)e.getSource()).getSelectedIndex();
if(index == 0){
//panelAnswers.removeAll();
file = "";
try {
in = new BufferedReader(new FileReader("openSave.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tPane.setText(file);
System.out.println("I am outputting!");
}
else if(index == 1){
//panelAnswers.removeAll();
file = "";
try {
in = new BufferedReader(new FileReader("format.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
//String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tPane.setText(file);
System.out.println("2nd item selected");
}
else{
//panelAnswers.removeAll();
file = "";
try {
in = new BufferedReader(new FileReader("showInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tPane.setText(file);
System.out.println("3rd item selected");
}
}
});
JScrollPane scroll1 = new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll = new JScrollPane(tPane,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scroll1, scroll);
pane.setAutoscrolls(true);
pane.setOpaque(true);
panelQuestions.setMinimumSize(new Dimension(259,50));
panelQuestions.setBackground(new Color(0,0,0,0));
panelAnswers.setMinimumSize(new Dimension(600,30));
pane.setOneTouchExpandable(true);
pane.setDividerLocation(290);
scroll1.setBackground(new Color(0,0,0,0));
//Border border = new Border();
//scroll1.setBorder(BorderFactory.createLineBorder(Color.black));
//open the frame in the middle of the desktop.
Dimension desktopSize = desk.getSize();
Dimension jInternalFrameSize = frame.getSize();
frame.setLocation((desktopSize.width - jInternalFrameSize.width)/2, (desktopSize.height- jInternalFrameSize.height)/2);
frame.add(pane);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e1) {
}
}
else{
try {
//frame.setIcon(true);
//frame.setMaximizable(true);
frame.setSelected(true);
frame.moveToFront();
//frame.toFront();
} catch (PropertyVetoException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame(String title) {
super(title, true,true, true, true);
setSize(800,500);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition * openFrameCount);
}
}
You are trying to load the file from the filesystem. Instead, you need to load it via a classloader.
Getting Resources from a jar: classloader vs class resourceasstream
Edit: I'm assuming that the executable jar contains this text file. Is that the case?
What am I trying to do
Simulate a socialnetwork program,in which you can add your profile,change your status,your picture,add friends etc.The program must save it's content before closing in a file.
How do I intend to do it
As I can not append with ObjectOutputStream. I though of creating an ArrayList<SocialProfiles> (SocialProfiles) in this case are the profiles which I am trying to save.
I want to load the profiles from the file to the ArrayList when the program starts,and when I am done adding profiles, I want to write the profiles from the ArrayList back to the file.
I am using the size of the array as an index.Example when it first writes to the array,it writes to index 0.When it has 1 element it writes to index 1 etc etc.
What is not going as it is supposed to?
The program does not load the data from the file to the array.
What do I call at Main
try {
fileoutput = new FileOutputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
output = new ObjectOutputStream(fileoutput);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fileinput = new FileInputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
System.out.println("File database.dat nuk ekziston");
}
try {
input = new ObjectInputStream(fileinput);
} catch (IOException e2) {
}
loadData();
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
new Thread()
{
#Override
public void run()
{
writeData();
try {
fileinput.close();
fileoutput.close();
input.close();
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
}.start();
}
});
Methods
public void loadData(){
try{
while (true)
{
SocialProfile temp;
temp = (SocialProfile)input.readObject();
profiles.add(profiles.size(),temp);
}
}
catch(NullPointerException e){
}
catch(EOFException e){
System.out.println("U arrit fund-i i file");
} catch (ClassNotFoundException e) {
System.out.println("Objekt-i i lexuar nuk u konvertua dot ne klasen e caktuar");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeData(){
SocialProfile temp;
for(int i=0;i<profiles.size();i++){
temp=profiles.get(i);
try {
output.writeObject(temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try to serialize/deserialize whole array instead of each object.
public void serializeData(String filename, ArrayList<SocialProfile>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}
}
private ArrayList<SocialProfile> deserializeData(String filename){
try{
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
return (ArrayList<SocialProfile>)ois.readObject();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}catch(ClassNotFoundException e){
...
}
}
I'm working on a really simple Java Client / Server system (Just to get my feet wet with sockets). For some reason, I keep getting a "Socket is closed" error... here is my code..
Server File
public class Server {
public static ServerSocket s = null;
public static void main(String[] args) {
//Create the server socket
int port = 1111;
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
try {
s = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s.setSoTimeout(0);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Runnable r = new Runnable() {
public void run() {
while (true) {
Socket caught = null;
try {
caught = Server.s.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (caught == null) {
return;
}
InputStream is = null;
try {
is = caught.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
handleCommand(output, caught);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
public static void handleCommand(String in, Socket s1) {
if (in.equalsIgnoreCase("test")) {
System.out.println("Recieved Test Command..");
System.out.println("Sending response..");
PrintStream ps = null;
try {
ps = new PrintStream(s1.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
ps.close();
}
}
}
Client File
public class Client {
public static Socket s = null;
public static void main(String[] args) {
int port = 1111;
String server = "localhost";
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
if (args.length > 1) {
server = args[1];
}
try {
s = new Socket(server, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (s != null) {
Runnable r = new Runnable() {
public void run() {
while (true) {
InputStream is = null;
try {
is = s.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
PrintStream ps = null;
try {
ps = new PrintStream(s.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Sending Test message..");
try {
ps.println("test");
} catch (Exception e) {
System.out.println("Error: - " + e.getMessage());
}
}
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
}
I get the error in the client on line 41 and then a NullPointerException on line 46..
Thanks in advance for any help. I'm just trying to learn here.
in the server on line 61, when you do your first read, your client didn't had the oportunity to send data, so it don't stops in the loop and move forward to close the reader on line 68.
Try to create a class to handle incoming connections at the server, that makes easier to think about what to do in the server, something like ClientHandler would be a good choice ;)
have fun !
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.