Why doesn't "System.out.println" work in Android?

JavaAndroidPrintingConsoleSystem

Java Problem Overview


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");
    }

Java Solutions


Solution 1 - Java

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.

[https://content.screencast.com/users/davweb/folders/Snagit/media/04ab3404-7d58-4e6f-97c3-27c0637d8050/02.08.2010-09.37.55.png" width="480">][2]

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][3]:

> 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.

[2]: https://content.screencast.com/users/davweb/folders/Snagit/media/04ab3404-7d58-4e6f-97c3-27c0637d8050/02.08.2010-09.37.55.png "Click for full size" [3]: https://developer.android.com/reference/android/util/Log.html#ASSERT

Solution 2 - Java

Use the Log class. Output visible with LogCat

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

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;
        }
    }
}

Solution 6 - Java

it is not displayed in your application... it is under your emulator's logcat

Solution 7 - Java

System.out.println("...") is displayed on the Android Monitor in Android Studio

Solution 8 - Java

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! :)

Solution 9 - Java

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");

Solution 10 - Java

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.

  1. 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.

  2. 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.

  3. 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.

  1. 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.

  2. Android Console is designed to pop up when you write to it.

  3. Android Console will hide when you backpress.

Solution 11 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - JavaDave WebbView Answer on Stackoverflow
Solution 2 - JavaMaurits RijkView Answer on Stackoverflow
Solution 3 - JavakaushikSumanView Answer on Stackoverflow
Solution 4 - JavaMarcView Answer on Stackoverflow
Solution 5 - Java7heavenView Answer on Stackoverflow
Solution 6 - JavaALSPView Answer on Stackoverflow
Solution 7 - JavaWesos de QuesoView Answer on Stackoverflow
Solution 8 - JavaValentin FilyovView Answer on Stackoverflow
Solution 9 - JavaNut eaterView Answer on Stackoverflow
Solution 10 - Javauser13947194View Answer on Stackoverflow
Solution 11 - JavaRonak DesaiView Answer on Stackoverflow