I am making an app for android in Qt. So in order to use the Google API I need to implement Java. So I have looked through the QtNotifier example and I am trying to implement the same as a starter.
This Java example comes from the QtNotifier example aswell so it should work the same but it doesn't. I have tried to debug it using the Qt debugger but the breakpoints do not seem to trigger So I added println statements to see at which line it goes wrong. But this is not enough so I am trying to print a stacktrace using a catch/try clause.
I have implemented it like this:
package org.qtproject.qt5.example;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import java.lang.Object;
import java.io.Writer;
import java.io.StringWriter;
import java.io.PrintWriter;
public class NotificationClient extends org.qtproject.qt5.android.bindings.QtActivity
{
private static NotificationManager m_notificationManager;
private static Notification.Builder m_builder;
private static NotificationClient m_instance;
public NotificationClient()
{
System.out.println("it works2222");
m_instance = this;
}
public static void notify(String s)
{
System.out.println(s);
try {
if (m_notificationManager == null) {
System.out.println("1111");
m_notificationManager = (NotificationManager)m_instance.getSystemService(Context.NOTIFICATION_SERVICE);
System.out.println("2222");
m_builder = new Notification.Builder(m_instance);
System.out.println("3333");
m_builder.setContentTitle("A message from Qt!");
System.out.println("4444");
}
System.out.println("5555");
m_builder.setContentText(s);
System.out.println("6666");
m_notificationManager.notify(1, m_builder.build());
System.out.println("7777");
} catch(Exception e) {
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
e.printStackTrace(pw);
String errorDetail = writer.toString();
}
}
}
The output is:
I/System.out( 4768): test string
I/System.out( 4768): 1111
It would seem that m_instance is still null because "System.out.println("it works2222");" does not get called. But the error does not get caught.
Is it because this is an error that is not an exception?
I have also tried running the QtNotifier app but the printstatement inside.
public NotificationClient()
{
System.out.println("it works2222");
m_instance = this;
}
But that is also not called in the QtNotifier app.
My question is: How can I trace this error?
In Java, there are both Errors and Exceptions. Normally, an Error is significant enough that your program should just crash and exit. However, for debugging purposes, if you want to catch both you should
catch (Throwable t)
{
t.printStackTrace();
}
to get information on both.
Related
I want to have a setting system that I can read write and use variables from the are stored in a file.
To summarize, There is a class and inside that class is a list of settings.
When I make a setting I want to add it to the list so that I can write it to the text file later.
I also want to be able to get the setting value without casting it which would use generics.
So for boolSetting I would only need to do boolSetting.get() or boolSetting.value ect
To start with code I have already written I have the code to read and write to the file. This works perfect (I think). I just need help with the setting part. Here is the read and write to file.
package winter.settings;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import net.minecraft.src.Config;
import winter.Client;
public class WinterSettings {
public static File WinterSetting;
public static void readSettings() {
try {
File WinterSetting = new File(System.getProperty("user.dir"), "WinterSettings.txt");
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(new FileInputStream(WinterSetting), "UTF-8"));
String s = "";
while ((s = bufferedreader.readLine()) != null)
{
System.out.println(s);
String[] astring = s.split(":");
Client.modules.forEach(m ->{
if(m.name==astring[0]) {
m.settings.forEach(setting ->{
if(setting.name==astring[1]) {
setting.value=astring[2];
}
});
}
});
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeSettings() {
try {
File WinterSetting = new File(System.getProperty("user.dir"), "WinterSettings.txt");
PrintWriter printwriter = new PrintWriter(new FileWriter(WinterSetting));
Client.modules.forEach(m ->{
m.settings.forEach(setting ->{
printwriter.println(m.name+":"+setting.name+":"+setting.value);
});
});
printwriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Pretty much how this works is I have a setting in a Module which just stores some information.
The setting has a name and a value
To write it I am just writing
The module name, the setting name, the setting value For example: ModuleName:SettingName:false
This works fine, but leads to the problem that I just don't know enough about generics. I can't find a way that works with writing reading and setting / getting. The setting should have a name and value. Some code I wrote is below I just don't know how to continue it.
public class Setting<T> {
public String name;
public T value;
public Setting(String name, T value) {
this.name = name;
this.value = value;
}
public T getValue() {
return value;
}
}
From here I have subclasses for each type of setting. Not sure if this is good programming or not.
Now I can set get / write, but when I read the value isn't updated correctly.
Right now I make a new setting like
private final BooleanSetting toggleSprint = new BooleanSetting("ToggleSprint", true);
There is one problem to this from what I can tell. First off when I try to add it to a list when initilizing I get an error.
Type mismatch: cannot convert from boolean to BooleanSetting.
In short: I need to be able to read write get and set a value in a setting object. This can be boolean / int / ect.
Above is some of my code to read / write to txt file. Setting class and what I have of making a new setting.
My 2 problems are that I read the settings correctly and when making them I can't add them to a list.
Use the Boolean.True static variable
new BooleanSetting("ToggleSprint", Boolean.TRUE);
or
Boolean.valueOf(true)
The following code is for reading or writing files with java, but:
Eclipse prints these errors:
buffer_1 cannot be resolved to a variable
file_reader cannot be resolved
also other attributes...
what is wrong in this code here:
//Class File_RW
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class File_RW {
public File_RW() throws FileNotFoundException, NullPointerException {
File file_to_read = new File("C:/myfiletoread.txt");
FileReader file_reader = new FileReader(file_to_read);
int nr_letters = (int)file_to_read.length()/Character.BYTES;
char buffer_1[] = new char[nr_letters];
}
public void read() {
file_reader.read(buffer_1, 0, nr_letters);
}
public void print() {
System.out.println(buffer_1);
}
public void close() {
file_reader.close();
}
public File get_file_to_read() {
return file_to_read;
}
public int get_nr_letters() {
return nr_letters;
}
public char[] get_buffer_1() {
return buffer_1;
}
//...
}
//main method # class Start:
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class Start {
public static void main(String[] args) {
File_RW file = null;
try {
file = new File_RW();
} catch (NullPointerException e_1) {
System.out.println("File not found.");
}
//...
}
}
I can't find any mistake. I have also tried to include a try catch statement into the constructor of the class "File_RW", but the error messages were the same.
Yes, there are errors in your code - which are of really basic nature: you are declaring variables instead of fields.
Meaning: you have them in the constructor, but they need to go one layer up! When you declare an entity within a constructor or method, then it is a variable that only exists within that constructor/method.
If you want that multiple methods can make use of that entity, it needs to be a field, declared in the scope of the enclosing class, like:
class FileRW {
private File fileToRead = new File...
...
and then you can use your fields within all your methods! Please note: you can do the actual setup within your constructor:
class FileRW {
private File fileToRead;
public FileRW() {
fileToRead = ..
but you don't have to.
Finally: please read about java language conventions. You avoid using "_" within names (just for SOME_CONSTANT)!
javacode already running...thx
same program edited with c++ in visual Studio express...
visit the stackoverflow entry link:
c++ file read write-error: Microsoft Visual C++ Runtime libr..debug Assertion failed, expr. stream.valid()
It seems that System.setOut() does not work in this test case.
Here are problem description.
test0 executes System.setOut(new PrintStream(byteBuffer)) so that it stores standard output.
test0 invokes AddChild1_wy_v1.main.
In the AddChild1_wy_v1.main, xml.addChild(null) generates an exception message.
The exception message should be stored in byteBuffer, but it seems it wasn't.. JVM stops running the test case once the exception message pops up. And the remaining code after AddChild1_wy_v1.main are not executed.
Is there a way for jvm to execute the remaining code in test0?
NanoAddChild1_wy_v1Tests.java
package tests;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import net.n3.nanoxml.*;
public class NanoAddChild1_wy_v1Tests extends TestCase {
public void test0() throws Exception { //addchild1.out
String result;
ByteArrayOutputStream byteBuffer;
byteBuffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(byteBuffer));
AddChild1_wy_v1.main(new String[] {"/home/junghyun/Dev/nanoxml/inputs/simple.xml"});
result = new String(byteBuffer.toByteArray());
assertEquals(result, "Exception in thread \"main\" java.lang.IllegalArgumentException: child must not be null\n\tat net.n3.nanoxml.XMLElement.addChild(XMLElement.java:165)\n\tat AddChild1_wy_v1.main(AddChild1_wy_v1.java:47)\n");
}
}
AddChild1_wy_v1.java
package tests;
import net.n3.nanoxml.IXMLParser;
import net.n3.nanoxml.IXMLReader;
import net.n3.nanoxml.StdXMLReader;
import net.n3.nanoxml.XMLElement;
import net.n3.nanoxml.XMLParserFactory;
import net.n3.nanoxml.XMLWriter;
public class AddChild1_wy_v1
{
public static void main(String args[])
throws Exception
{
if (args.length == 0) {
System.err.println("Usage: java DumpXML file.xml");
Runtime.getRuntime().exit(1);
}
IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
IXMLReader reader = StdXMLReader.fileReader(args[0]);
parser.setReader(reader);
XMLElement xml = (XMLElement) parser.parse();
xml.addChild (null);
(new XMLWriter(System.out)).write(xml);
}
}
There's 3 default streams:
System.in : InputStream
System.out :PrintStream
System.err :PrintStream
So to set each one there is 3 methods:
public static void setIn(InputStream in) {...}
public static void setOut(PrintStream out) {...}
public static void setErr(PrintStream err) {...}
To set System.err you must use System.setErr(yourStream);
For another question: you just need to use
try {
//throwing exception
} catch (Exception e) {
//act on exception
}
It seems to me that you never write that Exception at all.
You just throw it upwards. Try catch it and have ex.printStackTrace();
Also that will go to standard error, unless you specifically say otherwise.
As by your request I will leave the test0 method unaltered, you can use it the way it is.
in AddChild1_wy_v1.java:
public class AddChild1_wy_v1 {
public static void main(String args[]) // note that I don't throw the Exception.
{
try {
if (args.length == 0) {
System.err.println("Usage: java DumpXML file.xml");
Runtime.getRuntime().exit(1);
}
IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
IXMLReader reader = StdXMLReader.fileReader(args[0]);
parser.setReader(reader);
XMLElement xml = (XMLElement) parser.parse();
xml.addChild (null);
(new XMLWriter(System.out)).write(xml);
} catch (Exception any) {
any.printStackTrace(System.out); // note that I send the Stack Trace to standard out here.
}
}
}
Wrap your method call in a try-catch to continue past the exception:
try {
AddChild1_wy_v1.main(...);
} catch(Throwable t) {
t.printStackTrace();
}
// the rest of your code will execute
Exceptions are printed to standard error, not standard output. Try System.setErr.
Never post images of your code.
This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 8 months ago.
I am creating a class -- just a class, no main() and I am receiving the error of "unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown" at this line:
FileOutputStream outStr = new FileOutputStream(FILE, true);
I don't understand; I put in a try{} catch{} block and it's still reporting the error.
Additionally, it's also reporting an "illegal start of type" for the try and both catch lines, and it's also saying that ';' is expected for both catch lines.
I'm using the NetBean IDE, FYI.
Thank you for any help.
Here is the full code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.FileNotFoundException;
public class UseLoggingOutputStream
{
String FILE = "c:\\system.txt";
try
{
FileOutputStream outStr = new FileOutputStream(FILE, true);
}
catch(FileNotFoundException fnfe)
{
System.out.println(fnfe.getMessage());
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
}
You need to put the file processing statements inside a method:
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class UseLoggingOutputStream {
public void myMethod() {
String file = "c:\\system.txt";
try {
FileOutputStream outStr = new FileOutputStream(file, true);
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
}
}
}
All functional code needs to go into methods - I don't see a method in your code - that's the illegal start of type problem. The other compile errors should become clearer once you get the basics down.
public class Foo {
public void doSomething() {
//code here
}
}
Move this code to some method or at least to a static initializer block.
import java.io.*;
import java.util.*;
public class SortNames {
private String[] strings = new String[10];
private int counter;
public SortNames() {
ArrayList<String> names = new ArrayList<String>();
Scanner scan = null;
File f = null;
try{
f = new File("names.txt");
scan = new Scanner(f);
while(scan.hasNext()) names.add(scan.next());
}
finally{scan.close();}
Collections.sort(names);
for(String s:names) System.out.println(s);
}
}
Sorry if this isn't helpful to you, but I was able to solve this exact issue by adding " throws FileNotFoundException " to my method call that contained the FileWriter. I know this may not be helpful since you aren't using methods, but then again, maybe it is.
I'm trying to understand how to work with Skype using java (JSkype lib)
i use example (official site):
package testproj;
import net.lamot.java.jskype.general.AbstractMessenger;
import net.lamot.java.jskype.general.MessageListenerInterface;
import net.lamot.java.jskype.windows.Messenger;
import java.lang.Thread;
import java.lang.Exception;
import java.util.Date;
public class JSkype implements MessageListenerInterface {
private AbstractMessenger msgr = null;
public JSkype() {
msgr = new Messenger();
msgr.addListener(this);
msgr.initialize();
try {
Thread.sleep(5000);
msgr.sendMessage("MESSAGE echo123 test message");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new JSkype();
}
public void onMessageReceived(String str) {
System.out.println("RESULT: "+str);
}
}
after run, in console i have many information, but for me more intresting information, that I receive after send message:
RESULT: MESSAGE 21129 STATUS SENDING
RESULT: MESSAGE 21129 STATUS SENDING
RESULT: CHAT #my.name/$echo123;9797238991f90d78 ACTIVITY_TIMESTAMP 1294574640
and now I'm trying to understand, how to determine the success of sending a message?
yep, we need parsind result string.. but what is a number 21129? 9797238991f90d78? how i can know this number before start parsing?