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

Related Posts Plugin for WordPress, Blogger...