I have this idea, that anytime an unhandled exception occurs in my JavaFX program, that instead of relying on console output, I can display an alert to the user. I am thinking that perhaps I can capture the output from System.err to use. Here is what I have tried thus far.
PrintStream myStream = new PrintStream(System.err) {
#Override
public void println(String s) {
super.println(s);
Log.debugLog(s); //this function logs to a file and displays an alert to user
}
};
System.setErr(myStream);
This code segment works if I replace System.err with System.out, and System.setErr to System.setOut. However that is capturing System.out, not System.err. I suppose the better question would be, what exact function does System.err call when displaying an error to the console? So that may override it. Any tips are appreciated.
I think you have the wrong approach. If you want to display an alert to the user when there is an unhandled Exception, you can do that by setting a DefaultUncaughtExceptionHandler:
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
// show alert to user
e.printStackTrace();
// do whatever you want with the Exception e
});
You can create a JavaFX Alert customized to show an exception stack trace along with a brief message. This link shows the code for the below.
I have a Java program that is built, and is running as a standalone .Jar file. The last build was in start November, and it, along with the previous builds, have been running smoothly.
The function that has stopped working, is where the user wishes to print a receipt, and the program used to show a "Select printer" dialog screen.
But as of today, when the button that runs this function is clicked, nothing happens. The button click effects runs as they should, so the click is registered, but nothing else happens.
I have tried running the .jar file on both my own, and the users computer with same negative result.
However, when i run the project in IntelliJ, and click the button, everything works as it should, with no exceptions or warinings anywhere. I then tried rebuilding it using this very same code. But again, as a separate .jar file, nothing happens. The user, used the very same function as intended just 2 days ago, with the same .jar file that is not working now.
Edit: Opening the jar file in the commandwindow gives a NullPointerException at the line mentioned below.
A remote debug gives this explanation of the object beleived to cause the exception:
JavaFX PrinterJob Printer Microsoft Print to PDF
Collation = UNCOLLATED
Copies = 1
Sides = ONE_SIDED
JobName = JavaFX Print Job
Page ranges = null
Print color = COLOR
Print quality = NORMAL
Print resolution = Feed res=600dpi. Cross Feed res=600dpi.
Paper source = Paper source : Automatic
Page layout = Paper=Paper: A4 size=210.0x297.0 MM Orient=PORTRAIT leftMargin=54.0 rightMargin=54.0 topMargin=54.0 bottomMargin=54.0
Job Status = NOT_STARTED
public class PrintPage {
public void printSetup(Node node, PageOrientation or)
//The class where it prompts for the printer to be used.
{
Stage stage = new Stage();
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null) {
//Line below gives NullPointerException at the job.showPrintDialog(stage) item
if (job.showPrintDialog(stage)) print(job, node, or);
}
stage.close();
}
The errorstack leads from the line above to this part in the javafx PrinterJob class.
public synchronized boolean showPrintDialog(Window owner) {
// TBD handle owner
if (!isJobNew()) {
return false;
} else {
//This line is the next in the stack
return jobImpl.showPrintDialog(owner);
}
}
which leads to an error in:
com.sun.prism.j2d.print.J2DPrinterJob.showPrintDialog(J2DPrinterJob.java:161)
The only null item i see is the Page Ranges, which i can't seem to set.
I am building gui in netbeans... Or trying to is more like it. I keep getting an error in my code in the gray area that netbeans adds which evidently is a area that I can not edit.
it currently says this...
answerBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Answer Call" }));
answerBox.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
}
public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
answerBoxPopupMenuWillBecomeInvisible(evt);
}
public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
}
});
the error is on this line
answerBoxPopupMenuWillBecomeInvisible(evt);
In order to fix it when it says I need to remove answerBox from the beginning of the line, and I don't recall even adding a popupmenu in the first place so I am trying to figure out how to
hot to edit this line of code to see if it fixes my problem?
how can I delete things like this from the designer mode if they are giving me problems?
It appears that the event method answerBoxPopupMenuWillBecomeInvisible may no longer exist.
You could go into the "Events" tab of the property sheet and remove the associated event.
Failing that, you could open the file in something like NotePad++ and simply remove the entire listener registration code block
I have a text Field where the user enter a world to search a JTable when the user click a button called btnSearch.
every time I try to perform a search nothing happen and an Exception is thrown (see error below) when debug it show that the error occur at the if statement condition. could you please explain what I should do to fix the problem
the Error:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError:com.mysql.jdbc.StringUtils.isEmptyOrWhitespaceOnly(Ljava/lang/String;)Z
The Code behind the search button:
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String entry =txtSearchData.getText();
if (StringUtils.isEmptyOrWhitespaceOnly(entry)){
}else{
}
txtSearchData.setText(" ");
}
});
The only explanation I can find is you are using 2 mysql jdbc jars:
one that has StringUtils.isEmptyOrWhitespaceOnly defined, and which is used when you compile your code;
another one that does not have StringUtils.isEmptyOrWhitespaceOnly defined, and which is used when you run your code.
You should use only one version, both for compiling and running.
Check you project dependencies and make sure there is only one mysql jdbc driver.
I want to print something in console, so that I can debug it. But for some reason, nothing prints in my Android application.
How do I debug then?
public class HelloWebview extends Activity {
WebView webview;
private static final String LOG_TAG = "WebViewDemo";
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new MyWebChromeClient());
webview.loadUrl("http://example.com/");
System.out.println("I am here");
}
Correction:
On the emulator and most devices System.out.println gets redirected to LogCat and printed using Log.i(). This may not be true on very old or custom Android versions.
Original:
There is no console to send the messages to so the System.out.println messages get lost. In the same way this happens when you run a "traditional" Java application with javaw.
Instead, you can use the Android Log class:
Log.d("MyApp","I am here");
You can then view the log either in the Logcat view in Eclipse, or by running the following command:
adb logcat
It's good to get in to the habit of looking at logcat output as that is also where the Stack Traces of any uncaught Exceptions are displayed.
The first Entry to every logging call is the log tag which identifies the source of the log message. This is helpful as you can filter the output of the log to show just your messages. To make sure that you're consistent with your log tag it's probably best to define it once as a static final String somewhere.
Log.d(MyActivity.LOG_TAG,"Application started");
There are five one-letter methods in Log corresponding to the following levels:
e() - Error
w() - Warning
i() - Information
d() - Debug
v() - Verbose
wtf() - What a Terrible Failure
The documentation says the following about the levels:
Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.
Use the Log class. Output visible with LogCat
Yes it does. If you're using the emulator, it will show in the Logcat view under the System.out tag. Write something and try it in your emulator.
Of course, to see the result in logcat, you should set the Log level at least to "Info" (Log level in logcat); otherwise, as it happened to me, you won't see your output.
if you really need System.out.println to work(eg. it's called from third party library). you can simply use reflection to change out field in System.class:
try{
Field outField = System.class.getDeclaredField("out");
Field modifiersField = Field.class.getDeclaredField("accessFlags");
modifiersField.setAccessible(true);
modifiersField.set(outField, outField.getModifiers() & ~Modifier.FINAL);
outField.setAccessible(true);
outField.set(null, new PrintStream(new RedirectLogOutputStream());
}catch(NoSuchFieldException e){
e.printStackTrace();
}catch(IllegalAccessException e){
e.printStackTrace();
}
RedirectLogOutputStream class:
public class RedirectLogOutputStream extends OutputStream{
private String mCache;
#Override
public void write(int b) throws IOException{
if(mCache == null) mCache = "";
if(((char) b) == '\n'){
Log.i("redirect from system.out", mCache);
mCache = "";
}else{
mCache += (char) b;
}
}
}
it is not displayed in your application... it is under your emulator's logcat
System.out.println("...") is displayed on the Android Monitor in Android Studio
There is no place on your phone that you can read the System.out.println();
Instead, if you want to see the result of something either look at your logcat/console window or make a Toast or a Snackbar (if you're on a newer device) appear on the device's screen with the message :)
That's what i do when i have to check for example where it goes in a switch case code! Have fun coding! :)
I'll leave this for further visitors as for me it was something about the main thread being unable to System.out.println.
public class LogUtil {
private static String log = "";
private static boolean started = false;
public static void print(String s) {
//Start the thread unless it's already running
if(!started) {
start();
}
//Append a String to the log
log += s;
}
public static void println(String s) {
//Start the thread unless it's already running
if(!started) {
start();
}
//Append a String to the log with a newline.
//NOTE: Change to print(s + "\n") if you don't want it to trim the last newline.
log += (s.endsWith("\n") )? s : (s + "\n");
}
private static void start() {
//Creates a new Thread responsible for showing the logs.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while(true) {
//Execute 100 times per second to save CPU cycles.
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//If the log variable has any contents...
if(!log.isEmpty()) {
//...print it and clear the log variable for new data.
System.out.print(log);
log = "";
}
}
}
});
thread.start();
started = true;
}
}
Usage: LogUtil.println("This is a string");
I dont having fancy IDE to use LogCat as I use a mobile IDE.
I had to use various other methods and I have the classes and utilties for you to use if you need.
class jav.android.Msg. Has a collection of static methods.
A: methods for printing android TOASTS.
B: methods for popping up a dialog box.
Each method requires a valid Context. You can set the default context.
A more ambitious way, An Android Console. You instantiate a handle to the console in your app, which fires up the console(if it is installed), and you can write to the console. I recently updated the console to implement reading input from the console. Which doesnt return until the input is recieved, like a regular console.
A: Download and install Android Console( get it from me)
B: A java file is shipped with it(jav.android.console.IConsole). Place it at the appropriate directory. It contains the methods to operate Android Console.
C: Call the constructor which completes the initialization.
D: read<*> and write the console.
There is still work to do. Namely, since OnServiceConnected is not called immediately, You cannot use IConsole in the same function you instantiated it.
Before creating Android Console, I created Console Dialog, which was a dialog operating in the same app to resemble a console. Pro: no need to wait on OnServiceConnected to use it. Con: When app crashes, you dont get the message that crashed the app.
Since Android Console is a seperate app in a seperate process, if your app crashes, you definately get to see the error. Furthermore IConsole sets an uncaught exception handler in your app incase you are not keen in exception handling. It pretty much prints the stack traces and exception messages to Android Console. Finally, if Android Console crashes, it sends its stacktrace and exceptions to you and you can choose an app to read it. Actually, AndroidConsole is not required to crash.
Edit Extras
I noticed that my while APK Builder has no LogCat; AIDE does. Then I realized a pro of using my Android Console anyhow.
Android Console is design to take up only a portion of the screen, so you can see both your app, and data emitted from your app to the console. This is not possible with AIDE. So I I want to touch the screen and see coordinates, Android Console makes this easy.
Android Console is designed to pop up when you write to it.
Android Console will hide when you backpress.
Solution that worked for me:
Under Logcat. (To show Logcat if not already shown. Click View menu-->Tool Windows-->Logcat). It is shown as System.out not as System.out.println as you might expect it. Rebuild the app if you have not already.
In the picture, highlighted yellow shows the System.out and output "Hello again".
Recently I noticed the same issue in Android Studio 3.3. I closed the other Android studio projects and Logcat started working. The accepted answer above is not logical at all.