variables“快餐栏”可能没有被初始化

我得到这个错误消息,说Variable "snackbar" might not have been initialized

以下是我的MainActivity.java代码的一部分:

 public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (info != null && info.isConnected()) { final Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "WiFi change detected; updating information...", Snackbar.LENGTH_LONG) .setAction("DISMISS", new View.OnClickListener() { @Override public void onClick(View v) { snackbar.dismiss(); } }); snackbar.setActionTextColor(Color.BLUE); snackbar.show(); getWifi(); } } } 

我已经阅读了这里接受的Stack Overflow答案,这表明我在public class NetworkChangeReceiver extends BroadcastReceiver后立即初始化snackbar 。 所以,我改变了代码:

 /* no changes here */ @Override public void onReceive(Context context, Intent intent) { Snackbar snackbar = null; /* no changes here */ if (...) { snackbar = Snackbar.make(...); } /* no changes here */ } 

但是这给了我一个错误Variable "snackbar" is accessed from within inner class, needs to be declared final并且警告Method invocation "snackbar.dismiss()" may produce "java.lang.NullPointerException"

有关如何解决这个问题的任何build议? 谢谢!

拆分你的链式方法调用:

 final Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "WiFi change detected; updating information...", Snackbar.LENGTH_LONG); snackbar.setAction("DISMISS", new View.OnClickListener() { @Override public void onClick(View v) { snackbar.dismiss(); } }); 

这样,在创buildOnClickListener之前, snackbar是明确分配的。

作为解决方法

Variable "snackbar" is accessed from within inner class, needs to be declared final

你可以使这个variables成为最后一个元素的数组