I have that inner class shown under. This is for a client/server and I had nullpointer exception at the "println" from an PrintWriter. I have tried all I know to solve it but, unsuccessfully. Anyone can give me a tip or an idea for what I have to do. Thanks guys!
Here's the FULL CLASS code:
public class ChatClient extends JFrame{
private JTextField textToSend;
private Socket socket;
private PrintWriter writer
private String name;
private JTextArea receivedText;
private Scanner reader;
public ChatCliente(String name){
super("Chat: "+ name);
this.name = name;
Font font = new Font("Serif", Font.PLAIN, 20);
textToSend = new JTextField();
textToSend.setFont(font);
JButton btn = new JButton("Send");
btn.setFont(font);
btn.addActionListener(new Listener());
Container content = new JPanel();
content.setLayout(new BorderLayout());
content.add(BorderLayout.CENTER, textToSend);
content.add(BorderLayout.EAST, btn);
receivedText = new JTextArea();
receivedText.setFont(font);
JScrollPane scroll = new JScrollPane(receivedText);
getContentPane().add(BorderLayout.CENTER, scroll);
getContentPane().add(BorderLayout.SOUTH, content);
configureNetwork();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
}
private void configureNetwork(){
try{
socket = new Socket("127.0.0.1",5000);
writer = new PrintWriter(socket.getOutputStream());
reader = new Scanner(socket.getInputStream());
new Thread(new ServerThread()).start();
}catch (Exception e){}
}
private class Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
try{
String s = name;
String t = textToSend.getText();
System.out.println(name+" : "+ textToSend.getText());
writer.println(s+" : "+t);
writer.flush();
textToSend.setText("");
textToSend.requestFocus();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
private class ServerThread implements Runnable{
#Override
public void run() {
String text;
try{
while((text = reader.nextLine()) != null){
receivedText.append(text+"\n");
}
}catch(Exception e){}
}
}
}
'name' is not declared.
Maybe you meant:
String s = "name";
Just some stupid thing that happened to me: do not insert "/" in the name of your file, or it will of course look for an extra folder that probably isn't there.
int number = 1, total = 126;
String path = "some/path/found " + number + "/" + total;
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path, true)));
Related
public with sharing class SobjectByParams {
public SObject createSObject(String sObjectName, Map<String, String> fields) {
String invalidSObjectError = System.Label.invalid_Sobject_Name;
String invalidFieldError = System.Label.Invalid_Sobject_Field;
SObject newObject;
try {
newObject = (SObject) Type.forName(sObjectName).newInstance();
} catch (NullPointerException ex) {
throw new InvalidTypeNameException(invalidSObjectError);
}
for (String field : fields.keySet()) {
try {
newObject.put(field, fields.get(field));
} catch (SObjectException ex) {
throw new InvalidTypeNameException(invalidFieldError);
}
}
insert newObject;
return newObject;
}
public class InvalidTypeNameException extends Exception {
}
}
#IsTest
public with sharing class SobjectByParamsTest {
SobjectByParams sobjectByParams;
private static final String TestName = 'TestName';
private static final String BCity = 'Lviv';
private static final String LastName = 'Kapo';
private static final String Email = 'email';
#IsTest
static void createSObject() {
SobjectByParams sobjectByParams = new SobjectByParams();
Map<String, String> fields = new Map<String, String>();
fields.put('BillingCity', BCity);
Test.startTest();
SObject result = sobjectByParams.createSObject(TestName, fields);
Test.stopTest();
System.assertEquals(BCity, result.get(BCity));
}
}
SobjectByParams.InvalidTypeNameException: invalidSobjectNameError - PROBLEM
TEST WORKING on 53.33% but I need min 80%
I don`t know how to fix my problem.
Shouldn't TestName be a sObject name like Contact? Does this code work when you run it normally, does it insert anything or throw? Check/fix that and then you probably need a negative test too.
Make second test method
#isTest
static void testPassingBadData() {
SobjectByParams sobjectByParams = new SobjectByParams();
Map<String, String> fields = new Map<String, String>();
fields.put('BillingCity', BCity);
try{
sobjectByParams.createSObject('NoSuchObjectInTheSystem', fields);
System.assert(false, 'This should have failed and thrown exception');
} catch(Exception e){
System.assert(e.getMessage().contains(Label.Invalid_Sobject_Field));
}
}
I am using NYT's developers movie reviews API, and i am at the beginning where i just want to see a response. It appears that i get a NULL response which catches the exception that i will pinpoint on the code. " CharSequence text = "There was an error. Please try again";" to help you find it. Could someone please tell me what causes this problem.
NYT Documentation Link http://developer.nytimes.com/movie_reviews_v2.json#/Documentation/GET/critics/%7Bresource-type%7D.json
public class MainActivity extends AppCompatActivity {
private final String site = "https://api.nytimes.com/svc/movies/v2/reviews/search.json?query=";
public int count;
public int i;
public int j;
public int k;
public int n;
public int comas;
public int ingadded;
public String web2 = "";
public String istos;
public ArrayList<String> mylist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button next = (Button) findViewById(R.id.button);
final EditText edit_text = (EditText) findViewById(R.id.ing);
final TextView show_ing = (TextView) findViewById(R.id.show_ing);
final Button done = (Button) findViewById(R.id.button3);
final Button refresh = (Button) findViewById(R.id.refresh);
final Button delete = (Button) findViewById(R.id.delete);
final ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
//done move to next activity
done.setOnClickListener(new View.OnClickListener() {
#Override
//CHECK IF TEXT BOX IS EMPTY
public void onClick(View view) {
web2 = edit_text.getText().toString();
//check if there are ingredients added
if (web2 == "") {
Context context = getApplicationContext();
CharSequence text = "Search Bar is Empty!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Dialog.dismiss();
}
else {
//IF NOT CREATE THE LINK AND SEND IT TO LongOperation
web2 = edit_text.getText().toString();
//create link - MAYBE THE WAY API KEY MUST BE CALLED?
istos = site + web2 + "?api-key=xxxxxxxxxxxx";
Log.v("Showme=", istos);
web2 = "";
// WebServer Request URL
String serverURL = istos;
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
});
edit_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
edit_text.setHint("");
else
edit_text.setHint("Type the title of the movie");
}
});
private class LongOperation extends AsyncTask<String, String, Void> {
// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private Integer count;
private int add = 1;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView jsonParsedname = (TextView) findViewById(R.id.jsonParsedname1);
ArrayList<ArrayList<Integer>> numArray = new ArrayList<ArrayList<Integer>>();
int sizeData = 0;
protected void onPreExecute() {
//Start Progress Dialog (Message)
Dialog.setMessage("Finding Movies..");
Dialog.show();
try {
// Set Request parameter
data = "&" + URLEncoder.encode("data", "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Context context = getApplicationContext();
CharSequence text = "There was an error. Please try again";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Dialog.dismiss();
} else {
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
if (jsonResponse == null) {
jsonParsedname.setText("Wrong Input");
}
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("results");
I build table. I want to add data from active window. But a.getTabNum() and rest of returned vatiables have the value of null
Here is my code:
JButton add = new JButton();
add.setText("+");
add.setHorizontalAlignment(SwingConstants.TRAILING);
panel.add(add);
//When user clicks he can add new employee
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
AddEmp a = new AddEmp();
a.setSize(400,140);
a.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
a.setVisible(true);
String post = a.getPost();
String nameSurname = a.getNameSurname();
String tabNum= a.getTabNum();
Connection connect = null;
PreparedStatement statement1 = null;
try {
connect = DriverManager
.getConnection("jdbc:mysql://localhost/tabel?user=root&password=4499669");
statement1 = connect
.prepareStatement("insert into employee(tab_num, name_surname, position, id_dept) values(?, ?, ?, ?)");
int a1= Integer.parseInt(tabNum);
statement1.setInt(1, a1);
statement1.setString(2,nameSurname);
statement1.setString(3, post);
statement1.setInt(4, num);
statement1.executeUpdate();
// / List of departments
// ////////////////////////////////////////////////////////////////
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
connect.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
here is ma AddEmp class:`public class AddEmp extends JFrame{
private static final long serialVersionUID = 1L;
JTextField a = new JTextField(30);
JTextField b = new JTextField(27);
JTextField c = new JTextField(23);
AddEmp self = this;
JLabel a1 = new JLabel("Ф.И.О");
JLabel b1 = new JLabel("Должность");
JLabel c1 = new JLabel("Табельный номер");
JButton o = new JButton("OK");
public AddEmp(){
super("Добавление сотрудника");
setResizable(false);
JPanel p = new JPanel();
p.add(a1);
p.add(a);
p.add(b1);
p.add(b);
p.add(c1);
p.add(c);
o.setHorizontalAlignment(SwingConstants.RIGHT);
p.add(o);
getContentPane().add(p, BorderLayout.CENTER);
o.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
JOptionPane.showMessageDialog(null, "Сотрудник добавлен");
self.setVisible(false);
self.dispose();
}catch(Exception e){
e.printStackTrace();
}
}
});
}
public String getPost() {
return b.getText();
}
public String getNameSurname() {
return a.getText();
}
public String getTabNum() {
return c.getText();
}
}`
I am developing a simple Java IDE like Netbeans/Eclipse. My GUI includes two JTextArea component, one used as a TextEditor where the end user can type in his programs and the other used as an output window.
I am running the users programs by invoking the windows command prompt through Java Runtime and Process classes. I am also catching the IO streams of the process using the methods getInputStream(), getErrorStream(), getOutputStream().
If the program contains only the statements to print something onto the screen, I am able to display the output on the output window(JTextArea). But if it includes statements to read input from the user, then it must be possible for the user to type the expected input value via the output window and it must be sent to the process just as in Netbeans/Eclipse.
I also checked the following link
java: work with stdin/stdout of process in same time
Using this code, I am able to display only the statements waiting for input and not simple output statements. Also, only a single line is displayed on the output window at a time.
It would be great if anybody can help me to resolve this issue.
Thanks
Haleema
I've found the solution with little modification to the earlier post java: work with stdin/stdout of process in same time
class RunFile implements Runnable{
public Thread program = null;
public Process process = null;
private JTextArea console;
private String fn;
public RunFile(JTextArea cons,String filename){
console = cons;
fn=filename;
program = new Thread(this);
program.start();
}
#Override
public void run() {
try {
String commandj[] = new String[4];
commandj[0] = "cmd";
commandj[1]="/C";
commandj[2]="java";
commandj[3] = fn;
String envp[] = new String[1];
envp[0]="path=C:/Program Files (x86)/Java/jdk1.6.0/bin";
File dir = new File("Path to File");
Runtime rt = Runtime.getRuntime();
process = rt.exec(commandj,envp,dir);
ReadStdout read = new ReadStdout(process,console);
WriteStdin write = new WriteStdin(process, console);
int x=process.waitFor();
console.append("\nExit value: " + process.exitValue() + "\n");
}
catch (InterruptedException e) {}
catch (IOException e1) {}
}
}
class WriteStdin implements Runnable{
private Process process = null;
private JTextArea console = null;
public Thread write = null;
private String input = null;
private BufferedWriter writer = null;
public WriteStdin(Process p, JTextArea t){
process = p;
console = t;
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
write = new Thread(this);
write.start();
console.addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyTyped(java.awt.event.KeyEvent e){
//save the last lines for console to variable input
if(e.getKeyChar() == '\n'){
try {
int line = console.getLineCount() -2;
int start = console.getLineStartOffset(line);
int end = console.getLineEndOffset(line);
input = console.getText(start, end - start);
write.resume();
} catch (BadLocationException e1) {}
}
}
});
console.addCaretListener(new javax.swing.event.CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
console.setCaretPosition(console.getDocument().getLength());
throw new UnsupportedOperationException("Not supported yet.");
}
});
console.addFocusListener(new java.awt.event.FocusAdapter() {
#Override
public void focusGained(java.awt.event.FocusEvent e)
{
console.setCaretPosition(console.getDocument().getLength());
}
});
}
#Override
public void run(){
write.suspend();
while(true){
try {
//send variable input in stdin of process
writer.write(input);
writer.flush();
} catch (IOException e) {}
write.suspend();
}
}
}
class ReadStdout implements Runnable{
public Thread read = null;
private BufferedReader reader = null;
private Process process = null;
private JTextArea console = null;
public ReadStdout(Process p,JTextArea t){
process = p;
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
console = t;
read = new Thread(this);
read.start();
}
public void run() {
String line;
try {
while((line = reader.readLine())!=null)
console.append(line+"\n");
}catch (IOException e) {}
}
}
JPanel p2 = new JPanel(new GridLayout(6,1));
ButtonGroup tubtype = new ButtonGroup();
JRadioButton roundrButton = new JRadioButton("Round", true);
tubtype.add(roundrButton);
JRadioButton ovalrButton = new JRadioButton("Oval", false);
tubtype.add(ovalrButton);
calcButton = new JButton("Calculate Volume");
exitButton = new JButton("Exit");
hlength = new JTextField(5);
hwidth = new JTextField(5);
hdepth = new JTextField(5);
hvolume = new JTextField(5);
lengthLabel = new JLabel("Enter the tub's length (ft):");
widthLabel = new JLabel("Enter the tub's width (ft):");
depthLabel = new JLabel("Enter the tub's depth (ft):");
volumeLabel = new JLabel("The tub's volume (ft^3):");
p2.add(roundrButton);
p2.add(ovalrButton);
p2.add(lengthLabel);
p2.add(hlength);
p2.add(widthLabel);
p2.add(hwidth);
p2.add(depthLabel);
p2.add(hdepth);
p2.add(volumeLabel);
p2.add(hvolume);
p2.add(calcButton);
p2.add(exitButton);
tab.addTab( "Hot Tubs", null, p2, " Panel #1" );
calcButtonHandler2 ihandler =new calcButtonHandler2();
calcButton.addActionListener(ihandler);
exitButtonHandler ghandler =new exitButtonHandler();
exitButton.addActionListener(ghandler);
FocusHandler hhandler =new FocusHandler();
hlength.addFocusListener(hhandler);
hwidth.addFocusListener(hhandler);
hdepth.addFocusListener(hhandler);
hvolume.addFocusListener(hhandler);
// add JTabbedPane to container
getContentPane().add( tab );
setSize( 550, 500 );
setVisible( true );
}
public class calcButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
DecimalFormat num =new DecimalFormat(",###.##");
double sLength, sWidth, sdepth, Total;
sLength = Double.valueOf(plength.getText());
sWidth =Double.valueOf(pwidth.getText());
sdepth =Double.valueOf(pdepth.getText());
if(e.getSource() == pcalcButton) {
Total = sLength * sWidth * sdepth;
pvolume.setText(num.format(Total));
try{
String value=pvolume.getText();
File file = new File("output.txt");
FileWriter fstream = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Length= "+sLength+", Width= "+sWidth+", Depth= "+sdepth+" so the volume of Swimming Pool is "+value);
out.newLine();
out.close();
}
catch(Exception ex){}
}
}
}
public class calcButtonHandler2 implements ActionListener {
public void actionPerformed(ActionEvent g) {
DecimalFormat num =new DecimalFormat(",###.##");
double cLength, cWidth, cdepth, Total;
cLength = Double.valueOf(hlength.getText());
cWidth = Double.valueOf(hwidth.getText());
cdepth = Double.valueOf(hdepth.getText());
try
{
AbstractButton roundrButton;
if(roundrButton.isSelected())
{
Total = Math.PI * Math.pow(cLength / 2.0, 2) * cdepth;
}
else
{
Total = Math.PI * Math.pow(cLength * cWidth, 2) * cdepth;
}
hvolume.setText(""+num.format(Total));
}
catch(Exception ex){}
}
}
}
class exitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent g){
System.exit(0);
}
}
class FocusHandler implements FocusListener {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
}
public static void main( String args[] )
{
Final tabs = new Final();
tabs.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
I am getting an error that says my roundrButton may not have been initialized. Please help.
The problem is these lines here:
try
{
AbstractButton roundrButton;
if(roundrButton.isSelected())
{
You're declaring a variable called roundrButton, and then attempting to call .isSelected() on it. You never assign anything to roundButton, though, so it is going to be null.
It seems like you might want to be referring to the roundrButton that you declared earlier. Have you considered making it a field of your class?
The error happens here:
try {
AbstractButton roundrButton;
if (roundrButton.isSelected()) {
You declared a variable called roundrButton but did not assign any object to it.
Then you called a method on, well, who knows? There is no object on which to call the method, because the variable roundrButton never received a value.
I guess your problem is in method actionPerformed of class calcButtonHandler2 :
try {
AbstractButton roundrButton;
if(roundrButton.isSelected())
roundrButton is indeed not initialized and it will lead to a NullPointerException at runtime.