2015-10-28 55 views
0

我想使用format()来打印一个字符串,但它的失败。错误是:空对象引用与控制台类

java.lang.NullPointerException:试图调用虚拟方法'java.io.Console java.io.Console.format(java.lang.String,java.lang.Object [])'on a空对象引用

下面是代码片段。希望提供任何提示

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); 
     } 
    } 
} 
+0

这可能帮助:http://stackoverflow.com/questions/4203646/system-console-returns-null –

+0

我敢肯定,Android不给你'Console'。 – chrylis

回答

0

System.console()返回对与JVM关联的控制台设备的引用。如果您尚未使用控制台设备配置JVM,并且没有默认配置JVM,则System.console()可能会返回空引用。请参阅javadoc for java.io.Console。它很好地概述了为什么System.console()将返回null。作为System.console()的替代方法,请尝试使用System .out.println()或System .err.println();否则,请使用System .out.println()或System .err.println();

另一位用户询问the same question并收到有用的回复。

0

使用此代码:

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

     } 
    } 
} 
+0

感谢您的所有意见,我可以确认System.console()确实返回null并且是问题的基础 –

+0

我通过创建使用KLOG_ERROR()的NDK可执行文件解决了此问题。适用于我的使用案例,抛出这个以防其他人帮助 –