0

I'm trying to use the format() to print a string, but it's failing. The error is:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Console java.io.Console.format(java.lang.String, java.lang.Object[])' on a null object reference

Here's the code snippet. Would appreciate any tips

public class BootNotifier extends BroadcastReceiver
{
    public String TAG = "BootNotifier";
    Console console = System.console();
    String fmt = "%s";
    String msg = "Android boot completed successfully";

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.e(TAG, "onReceive");
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
        {
            Log.e(TAG, "onReceive: BOOT_COMPLETED");
            console.format(fmt, msg);
        }
    }
}
droid_dev
  • 303
  • 4
  • 15

2 Answers2

0

System.console() returns a reference to the console device associated with the JVM. If you haven't configured your JVM with a console device, and if one is not configured by default, it is likely that System.console() is returning a null reference.

Take a look at the javadoc for java.io.Console. It gives a good overview of why System.console() will return null.

As an alternative to System.console(), try System.out.println() or System.err.println();

Another user asked the same question and received helpful responses.

Community
  • 1
  • 1
StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31
0

Use this code :

    public class BootNotifier extends BroadcastReceiver
    {
    public String TAG = "BootNotifier";
    String fmt = "%s";
    String msg = "Android boot completed successfully";

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.e(TAG, "onReceive");
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
        {
            Log.e(TAG, "onReceive: BOOT_COMPLETED");
            System.out.println(String.format(fmt, 5));
            //As System.out.println() is not recommended to use in Android ,So You can use below code in place of System.out.println()
             Log.d(fmt,"5");

        }
    }
}
Shishupal Shakya
  • 1,632
  • 2
  • 18
  • 41
  • Thanks for all the comments, I can confirm that System.console() is indeed returning null & is the basis of the problem – droid_dev Oct 28 '15 at 17:57
  • I solved this issue by creating a NDK executable that uses KLOG_ERROR(). Works for my use case, throwing this out in case it helps anyone else – droid_dev Nov 03 '15 at 18:33