Android: Showing System.out messages to console


In Java, we use System.out or System.err.println() to show messages in the console. However, these don’t work in Android. These methods do not produce errors on compilation and does nothing during runtime. Chris Glover made this nifty class to actually be able to use System.out and System.err in your programming needs.


package ***;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.util.Log;

public class LogTool extends OutputStream {
  private ByteArrayOutputStream bos = new ByteArrayOutputStream();
  private String name;
  
  public LogTool(String name)   {
    this.name = name;
  }
  
  @Override
  public void write(int b) throws IOException {
    if (b == (int)'\n') {
  String s = new String(this.bos.toByteArray());
  Log.v(this.name, s);
  this.bos = new ByteArrayOutputStream();
    } else {
    this.bos.write(b);
    }
  }
}

At the startup of your code, use these lines


System.setErr(new PrintStream(new LogTool("System.err")));
System.setOut(new PrintStream(new LogTool("System.out")));

Then you can use System.out and System.err.println(). If you want to convert Exception messages generated from the printStackTrace() method of Exception classes, use this Exception to String method converter that I have.


public static String getExceptionStackTraceAsString(Exception exception) {
  StringWriter sw = new StringWriter();
  exception.printStackTrace(new PrintWriter(sw));
  return sw.toString();
}

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

Related Posts with Thumbnails

7 Responses to “Android: Showing System.out messages to console”

Pages: [1] 2 » Show All

  1. 1
    Bruce Says:

    Hi… I was very interested to try this, since I am an Android newbie, but it doesn’t seem to work for me. I see no expected output in the Android emulator.
    In my code is:

    System.setErr(new PrintStream(new LogTool(“System.err”)));
    System.setOut(new PrintStream(new LogTool(“System.out”)));

    System.out.println(“Hello from System.out.println”);
    System.out.print(“Another string” + ‘\n’);
    System.err.println(“Hello from System.err”);

    Next step: run this in the debugger? Not sure how much that will help.

  2. 2
    tech Says:

    hi bruce, i stopped using android a long time ago, sorry can’t help since i also uninstalled my eclipse gui program.

    when i tried that, it did work for me.

  3. 3
    Bruce Says:

    That was fast! Well, it turns out I can see these messages using LogCat. So that gets me started. Thanks for the code…

  4. 4
    tech Says:

    welcome man

  5. 5
    consoles mobiles Says:

    evittez de commander des articles sur consoles mobiles c’est des escrocs

Pages: [1] 2 » Show All

Leave a Reply

Spam protection by WP Captcha-Free